반응형

1. $(document).ready()

- 외부 리소스. 이미지와는 상관 없이 브라우저가 DOM (document object model) 트리를 생성한 직후 실행
- window.load() 보다 더 빠르게 실행되고 중복 사용하여 실행해도 선언한 순서대로 실행됨
  

2. $(window).load()

- DOM의 standard 이벤트
- html의 로딩이 끝난 후에 시작
- 화면에 필요한 모든 요소(css, js, image, iframe etc..)들이 웹 브라우저 메모리에 모두 올려진 다음에 실행됨
- 화면이 모두 그려진 다음의 메세징이나 이미지가 관련 요소가 모두 올려진 다음의 애니메이션에 적합함
- 전체 페이지의 모든 외부 리소스와 이미지가 브러우저에 불려운 이후 작동하게 되어 이미지가 안뜨너가 딜레이가 생길 때에는 그만큼의 시간을 기다려야 함
- 외부 링크나 파일 인크루트시 그 안에 window.load 스크립트가 있으면 둘 중 하나만 적용됨
- body onload 이벤트와 같이 body에서 onload 이벤트를 쓰게 되면 모든 window.load() 가 실행되지 않는 현상이 발생함
 

* window > document
- document는 window의 자식 객체
  (window의 자식 객체 : document, self, navigator, screen, forms, history, location etc..)
- document : html의 요소들이나 속성들에 접근할 시 사용하는 객체

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(window).load(function() {
    console.log("console> window.onloade() 첫번째");
});
 
$(window).load(function() {
    console.log("console> window.onload() 두번째");
});
 
$(document).ready(function() {
    console.log("console> document.ready() 첫번째");
});
 
$(document).ready(function() {
    console.log("console> document.ready() 두번째");
});
</script>
 
</head>
<body>
 
</body>
</html>
반응형
반응형

*  li에서 텍스트 추출, 공백제거


$(function(){
    var value1 = '      abc     ';
    var value2 = $(":text").val();
    //공백제거 전
    alert("value1 : " + value1+"\n"+"value2 : " + value2);
     
    value1 = $.trim(value1);
    value2 = $.trim(value2);
    //공백제거 후
    alert("value1 : " + value1+"\n"+"value2 : " + value2);
})

<!doctype html>
<html lang="ko">
 <head>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
  <meta http-equiv="Content-Type" content="text/html";charset="utf-8"/>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
	ul{list-style-type: none;}
  </style>
 </head>
 <body>

  <ul id="menu1">
	<li>철수1</li>
	<li>영희1</li>
	<li>길동1</li>
	<li>둘리1</li>
  </ul>

  <ul id="menu2">
	<li>철수2</li>
	<li>영희2</li>
	<li>길동2</li>
	<li>둘리2</li>
  </ul>
  

   <script>	
   $("#menu2 li").each(function( index, element ) {
     console.log($(this).text());
   });
  </script>

 </body>
</html>
반응형
반응형

https://api.jquery.com/data/

 

.data() | jQuery API Documentation

Description: Return arbitrary data associated with the first element in the jQuery collection, as set by data() or by an HTML5 data-* attribute. The .data() method allows us to read data previously associated with DOM elements. We can retrieve several dist

api.jquery.com

일치하는 요소와 연결된 임의의 데이터를 저장하거나 일치하는 요소 집합의 첫 번째 요소에 대한 명명된 데이터 저장소의 값을 반환합니다.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>data demo</title>
  <style>
  div {
    color: blue;
  }
  span {
    color: red;
  }
  </style>
  <script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
 
<div>
  The values stored were
  <span></span>
  and
  <span></span>
</div>
 
<script>
$( "div" ).data( "test", { first: 16, last: "pizza!" } );
$( "span" ).first().text( $( "div" ).data( "test" ).first );
$( "span" ).last().text( $( "div" ).data( "test" ).last );
</script>
 
</body>
</html>

https://jsfiddle.net/mill01/moegwyp3/

 

jquery .data() - JSFiddle - Code Playground

 

jsfiddle.net

반응형
반응형

1. CheckBox 체크

$('#ckBox').prop('checked',true);
$('input:checkbox[name="네임"]').prop('checked',true);

첫 번째 라인과 같이 체크박스의 id를 지정해서 체크하여도 되고, 두 번째 라인과 같이 name, id 등을 선택하여 체크할 수 있다.

true로 설정하면 체크가 되고, false로 설정하면 체크가 해제 된다.

2. CheckBox 체크여부 확인

$('#ckBox').is(':checked');

.is(':checked') 를 이용하여 체크되어 있는지 아닌지를 알 수 있다.

(true : 체크되어 있음, false : 체크되어 있지 않음)

3. CheckBox 전체 체크

<div>전체<input type="checkbox" id="allCk"></div>
<div>테스트1<input id="ck1" type="checkbox"></input></div>
<div>테스트2<input id="ck2" type="checkbox"></input></div>
<div>테스트3<input id="ck3" type="checkbox"></input></div>

위와 같은 checkbox가 있을 때, 전체 체크하는 방법은 간단하다.

	$('#allCk').click(function(){
		var checked = $('#allCk').is(':checked');
		
		if(checked)
			$('input:checkbox').prop('checked',true);
	});

allCk 체크박스를 클릭 했을 때, allCk가 체크되어 있다면 checkbox를 전부 다 true로 해주면 된다.

 

 

테스트 소스

<!DOCTYPE html>
<html>
<head>
	<script src="./jquery-3.4.1.min.js"></script>
</head>

<div>전체<input type="checkbox" id="allCk"></div>
<div>테스트1<input id="ck1" type="checkbox"></input></div>
<div>테스트2<input id="ck2" type="checkbox"></input></div>
<div>테스트3<input id="ck3" type="checkbox"></input></div>

<button type="button" id="btn1">1번 체크/언체크</button>
<button type="button" id="btn2">2번 체크/언체크</button>
<button type="button" id="btn3">3번 체크/언체크</button>
<script>
	$('#btn1').click(function(){
		var checked = $('#ck1').is(':checked');
		$('#ck1').prop('checked',!checked);
	});
	
	$('#btn2').click(function(){
		var checked = $('#ck2').is(':checked');
		$('#ck2').prop('checked',!checked);
	});
	
	$('#btn3').click(function(){
		var checked = $('#ck3').is(':checked');
		$('#ck3').prop('checked',!checked);
	});
	
	$('#allCk').click(function(){
		var checked = $('#allCk').is(':checked');
		
		if(checked)
			$('input:checkbox').prop('checked',true);
	});
</script>
반응형
반응형

How TO - Create a Draggable HTML Element

https://www.w3schools.com/howto/howto_js_draggable.asp

 

How To Create a Draggable HTML Element

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

https://jqueryui.com/draggable/

 

Draggable | jQuery UI

Draggable Allow elements to be moved using the mouse. Enable draggable functionality on any DOM element. Move the draggable object by clicking on it with the mouse and dragging it anywhere within the viewport. view source 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1

jqueryui.com

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Draggable - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <style>
  #draggable { width: 150px; height: 150px; padding: 0.5em; }
  </style>
  <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
  <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
  <script>
  $( function() {
    $( "#draggable" ).draggable();
  } );
  </script>
</head>
<body>
 
<div id="draggable" class="ui-widget-content">
  <p>Drag me around</p>
</div>
 
 
</body>
</html>
반응형
반응형

each()문을 써야하는 이유는 무엇일까 특징을 살펴보자?

1. 일반 for문보다 가독성이 좋다
2. 객체형을 다루기가 쉽다.
3. Array 객체에서 사용가능
4. 빠른편이다.
5. 리턴값을 받지 못한다.

 

for, foreach, each 

var arr= [ 
			{name : '알리송', backnumber : '1'}
          , {name : '반다이크', backnumber : '4'} ];

//for문
for (var i = 0; i <arr.length; i++) {
  console.log('element', i, arr[i]);
  console.log(arr[i].name);
  console.log(arr[i].backnumber);
  console.log(arr[i].name + arr[i].backnumber);
};


foreach문
arr.forEach (function (el, index) {
  console.log('element', index, el);
  console.log(el.name);
  console.log(el.backnumber);
  console.log(el.name + el.backnumber);
});


$.each문
$.Each (arr, function (index, el) {
  console.log('element', index, el);
  console.log(el.name);
  console.log(el.backnumber);
  console.log(el.name + el.backnumber);
});
반응형
반응형

How copy and paste excel columns to HTML table with inputs?

엑셀의 내용 카피해서 웹화면 input에 순서대로 붙여넣기.

 

https://www.codeproject.com/Questions/1212303/How-copy-and-paste-excel-columns-to-HTML-table-wit

 

[Solved] How copy and paste excel columns to HTML table with inputs? - CodeProject

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900

www.codeproject.com

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>

</head>

<body>
    <table id="example" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
        </thead>
        <tbody>
            <tr>
                <td><input  type="text"></td>
                <td><input type="text"></td>
                <td><input  type="text"></td>
            </tr>
            <tr>
                <td><input type="text"></td>
                <td><input type="text"></td>
                <td><input type="text"></td>
            </tr>
            <tr>
                <td><input type="text"></td>
                <td><input type="text"></td>
                <td><input type="text"></td>
            </tr>
        </tbody>
    </table>

    <script>
        $(document).ready(function () {
            $('td input').bind('paste', null, function (e) {
                $txt = $(this);
                setTimeout(function () {
                    var values = $txt.val().split(/\s+/);
                    var currentRowIndex = $txt.parent().parent().index();
                    var currentColIndex = $txt.parent().index(); 
                    
                    var totalRows = $('#example tbody tr').length;
                    var totalCols = $('#example thead th').length;
                    var count =0;
                    for (var i = currentColIndex; i < totalCols; i++) {
                        if (i != currentColIndex)
                            if (i != currentColIndex)
                                currentRowIndex = 0;
                        for (var j = currentRowIndex; j < totalRows; j++) {                           
                            var value = values[count];
                            var inp = $('#example tbody tr').eq(j).find('td').eq(i).find('input');
                            inp.val(value);
                            count++;
                           
                        }
                    }


                }, 0);
            });
        });
    </script>

</body>
</html>

 

반응형
반응형

jquery ,  sortable, 안에 텍스트는 드래그 가능하게.  bootstrap sortable inner text dragable

 

https://jqueryui.com/sortable/

 

Sortable | jQuery UI

Sortable Reorder elements in a list or grid using the mouse. Enable a group of DOM elements to be sortable. Click on and drag an element to a new spot within the list, and the other items will adjust to fit. By default, sortable items share draggable prope

jqueryui.com

 

Sortable w/ Selectable Text

https://stackoverflow.com/questions/4070749/sortable-w-selectable-text

 

Sortable w/ Selectable Text

Is it possible to be able to have sortable elements, but still allow users to copy/paste the text inside the elements? <div class="sortable"> <div class="pseudo-sortable">Foo</di...

stackoverflow.com

 

What about putting your text in a <span>?

HTML

<ul id="sortable">
    <li><span>Item 1</span></li>
    <li><span>Item 2</span></li>
    <li><span>Item 3</span></li>
    <li><span>Item 4</span></li>
    <li><span>Item 5</span></li>
    <li><span>Item 6</span></li>
    <li><span>Item 7</span></li>
</ul>

jQuery

$("#sortable").sortable({
    revert: true,
    cancel: "#sortable li span"
});

Try it here: http://jsfiddle.net/6uXx8/

반응형

+ Recent posts