Get it on Google Play


Wm뮤 :: 자바스크립트 기본

블로그 이미지
가끔 그림그리거나 3D모델링하거나
취미로 로봇만드는
퇴직한 전자과 게임프로그래머
2020.3.48f1 , 2022.3.6f1 주로 사용
모카쨩
@Ahzkwid

Recent Comment

Archive


2021. 4. 5. 10:48 웹/자바스크립트

 

 

 

자바스크립트는 웹상에서 동작하는 언어로서

브라우저가 깔려있다면 어디서든지 사용가능하다

 

테스트는 여기서 해보면 편하다

https://codepen.io/pen/

 

Create a New Pen

...

codepen.io

 

 

 

다음은 hello world를 띄우는 예제이다

 

<script>

    alert('hello world');

</script>

 

<script>는 HTML에서 자바스크립트로 사용을 전환하겠다는 의미이고

</script>는 선언종료를 의미한다

 

 

다른방법

더보기

 

<script type="text/javascript">
    alert('hello world');
</script>

 

함수

function test() { 
//작동할 코드
}

 

변수
타입선언을 안 해도 되는등 다른언어에 비해 매우 유연하다

text = "텍스트";

 

배열

  arr=[];
  arr[0]="이미지링크1";
  arr[1]="이미지링크2";
  arr.length //길이

 

반복문

for(i=0;i<2;i++)
{
	//작동코드
}

 

로그

console.log("로그내용");

 

 

 

 

예제코드들

document.getElementById('레이어 이름').style.backgroundColor = "#ffffff";
//레이어 이름이나 div이름 같은 녀석에 접근하여 스타일의 배경색을 바꾸는 코드

document.body.style.backgroundImage = 'url(이미지 링크)';
//body의 배경이미지를 지정한 이미지 링크로 변경한다

 

 

 

HTML띄우기 예제

따옴표 내 따옴표는 \"로 표기해야 한다. 때문에 '문자열'도 많이 쓴다

//1번방법
document.write("<img src=\"이미지링크\">");

//2번방법
document.write('<img src="이미지링크">');

//3번방법
document.write("<img src='이미지링크'>");

 

 

시간 가져오기

 

let now = new Date();
let year  = now.getFullYear();  //0~1 (1월=0)
let month  = now.getMonth();  //0~1 (1월=0)
let date = now.getDate();
let day = now.getDay(); //0~6 (일요일=0,월요일=1)
let hour = today.getHours();
let min = today.getMinutes();
let second = today.getSeconds();
let ms = today.getMilliseconds();


if ((month+1==11)&&(date == 11))
{
    //빼빼로 데이일때 실행됨
}

 

 

 

addEventListener들

//마우스를 댈때
(function(img) 
{
  img.addEventListener('mouseover', function() 
  {
      img.src=imglinks2[imgIndex];
  });
})(img);

//마우스를 뗄때
(function(img) 
{
  img.addEventListener('mouseout', function() 
  {
      img.src=imglinks2[0];
  });
})(img);


//마우스를 클릭할때
(function(x,img) 
{
  img.addEventListener('click', function() 
  {
    imgIndex=x;
  });
})(x,img);

 

 

 

 

 

 

 

 

 

 

 

 

-아래부턴 HTML과 병합되어있다

 

버튼 누르면 이미지 변경

v1

더보기


id를 두개나 쓰는 킹받는방식이다

  <button id="testButton">
   <img id="testImg" src="이미지링크1">
  </button>
  
  
<script>
document.getElementById("testButton").addEventListener("click", function(){
    document.getElementById("testImg").src = "이미지링크2";
});

</script>

 

 

 

v2

v1보다 훨~씬 간결해져서 기분이 좋아짐

  <button onclick="test()">
   <img id="testImg" src="이미지링크1">
  </button>
  
  
<script>
    function test() { 
    document.getElementById("testImg").src = "이미지링크2";
    }
</script>

 

 

 

 

 

 

 

 

 

 

 

 


참고 : https://www.w3schools.com/html/html_table_borders.asp

 <table id="testTable" border="1" bordercolor="black" ></table><style>
   table
   { 
      border-collapse: collapse;
   }
   
</style>
<script>
  tb = document.getElementById("testTable");
  for(y=0;y<10;y++)
  {
    tr = document.createElement('tr');
    tb.appendChild(tr);
    for(x=0;x<10;x++)
    {
        td = document.createElement('td');
        td.innerText = x+","+y;
        tr.appendChild(td);
    }
  }
</script>

 

표 초기화

tb = document.getElementById("testTable");
while (tb.firstChild) {
    tb.removeChild(tb.firstChild);
}

 

 

 

클릭하면 동작하는 표



<table id="testTable" border="1" bordercolor="black" ></table><style>
   table
   { 
      border-collapse: collapse;
   }
   
</style>
<script>
  tb = document.getElementById("testTable");
  for(y=0;y<10;y++)
  {
    tr = document.createElement('tr');
    tb.appendChild(tr);
    for(x=0;x<10;x++)
    {
        td = document.createElement('td');
        td.innerText = x+","+y;
        (function(x, y, td) 
        {
          td.addEventListener('click', function() {
              alert('Clicked: ' + x + ',' + y);
          });
        })(x, y, td);
        tr.appendChild(td);
    }
  }
</script>

 

 

클릭하면 동작하는 표 (이미지)

 <table id="testTable" border="1" bordercolor="black" ></table><style>
   table
   { 
      border-collapse: collapse;
   }
   
</style>
<script>
  imglinks=[];
  imglinks[0]="이미지링크1";
  imglinks[1]="이미지링크2";
  
  tb = document.getElementById("testTable");
  for(y=0;y<4;y++)
  {
    tr = document.createElement('tr');
    tb.appendChild(tr);
    for(x=0;x<4;x++)
    {
        td = document.createElement('td');
        tr.appendChild(td);
        {
          img = document.createElement('img');
          img.src = imglinks[0];
          img.style.width = "50px";
          img.style.height = "50px";
          (function(x, y, img) 
          {
              img.addEventListener('click', function() 
              {
                  img.src=imglinks[1];
                  alert('Clicked: ' + x + ',' + y);
              });
          })(x, y, img);
          td.appendChild(img);
        }
    }
  }
</script>

 

 

 

배열처리

array = {0,1,2,0,1,2}

//C#의 ConvertAll과 동일
//결과 : 1, 2, 3, 1, 2, 3
array = array.map(x => x+1);

//C#의 FindAll과 동일
//결과 : 0, 0
array.filter(x => x==0);

' > 자바스크립트' 카테고리의 다른 글

자주 쓰는 자바 스크립트 코드  (0) 2023.12.01
자바스크립트 인풋패널 가져오기  (0) 2022.04.23
posted by 모카쨩

  • total
  • today
  • yesterday

Recent Post

저사양 유저용 블로그 진입