JQuery li click 이벤트 - jQuery li click ibenteu

on("click")과 click()의 차이점은 동적으로 이벤트를 바인딩할 수 있는지의 차이다.

on("click")은 동적으로 가능하고 click()은 최초에 선언된 element에만 동작한다.

아래 예제소스로 차이점을 알아보자.

<ul id="myTask">
    <li>Coding</li>
    <li>Answering</li>
    <li>Getting Paid</li>
</ul>

1. click() 이벤트

위 예제 소스에서 아무 li 태그나 클릭하면 아래 함수가 실행된다.

$("#myTask").children().click(function() {

    $(this).remove();
});

그러면 클릭한 li 태그에 바인딩된 click 이벤트가 실행되어 해당 li 태그가 remove() 될것이다.

여기서 아래소스처럼 동적으로 새로운 li 태그를 추가한 뒤,

$("#myTask").append("<li>New li tag</li>");

새로 추가된 "<li>New li tag</li>"를 클릭하면 click() 메소드는 동작하지 않는다.

왜냐하면 click() 이벤트는 최초에 페이지를 로딩할 때 선언되어 있던 element에 이벤트를 바인딩하고 나서는 더이상 동적으로 바인딩하지 않기 때문이다.

2. on("click") 이벤트

이때 .on("click") 이벤트를 사용하면 동적으로 이벤트를 바인딩시킬 수 있다.

아래 예제 소스처럼 부모태그인 'myTask'의 이벤트를 자식 태그인 li들에게 delegate시키는 방식으로 메소드를 구현하면 동적으로 추가된 태그에게 이벤트를 줄 수 있다.

$("#myTask").on("click", "li", function(event) {

    $("event.targe").remove();
});

즉, myTask 아래에 추가되는 태그는 모두 부모의 on("click") 이벤트를 물려받게 되는 것이다.

여기서 아래소스처럼 동적으로 새로운 li태그를 추가한 뒤,

$("#myTask").append("<li>New li tag</li>");

새로 추가된 "<li>New li tag</li>"를 클릭하면 .on("click") 이벤트가 동작하여 해당 태그는 remove()된다.

출처:

lookingfor.tistory.com/m/entry/JQuery-%ED%81%B4%EB%A6%AD-%EC%9D%B4%EB%B2%A4%ED%8A%B8-onclick-%EA%B3%BC-click-%EC%9D%98-%EC%B0%A8%EC%9D%B4

jQuery 를 사용하면 상당히 편한 부분이 많습니다.

오늘은 동적인 element에 이벤트를 바인딩하는 방법에 대해서 알아보겠습니다.

사실 jQuery에서 동적 요소에 이벤트를 주는 것은 어렵지 않습니다.

javascript를 예로 들면, 이벤트가 바인딩 되어있던 요소가 화면이 로딩 된 이후에 동적으로 추가 생성된다고 하면, elements를 추가하는 기능 이후에 또 이벤트를 바인딩해주어야 하는 번거로움이 있었습니다.

그러나 jQuery는 이러한 반복적인 코드처리를 해주지 않아도 알아서 이벤트를 붙여줍니다.

직접 코드로 보겠습니다.

jquery 로 이벤트 바인딩하는게 뭐가 어렵다고 이런 포스팅을 하나 싶은 분들도 계실텐데요.

넘기지 마시고 잘 보셔야 합니다~!

$('li').on('click', function(){
	//실행 코드
});

$('li').click(function(){
	//실행 코드
});

위에 예로 보여준 코드가 아마 처음 jQuery를 접하신 분들이 많이 사용하시는 방법일텐데요.

저렇게 element에 직접 이벤트를 줄 경우 해당 요소가 동적으로 추가 생성 되었을 때 이벤트가 붙어있지 않습니다.

그래서 javascript를 사용할 때 처럼 element를 추가하고 또다시 이벤트를 바인딩해주어야 하는 것이지요.

그러나 아래와 같이 이벤트를 주면 그러지 않아도 된다는 것입니다.

$('ul').on('click','li', function(){
	//실행 코드
});

이벤트를 줄 요소의 상위 element를 대상으로 하여 Click이벤트를 바인딩 하지만, 그 하위 요소인 li에 click이벤트를 지정해주는 겁니다. 여기서 li가 계속 동적으로 추가 된다고 하더라도 이미 ul은 계속 존재하는 상황이기 때문에 이벤트가 계속 살아있는 것입니다.

처음 스크립트를 시작할 때 간과할 수 있는 부분이지만, 나중에는 결국 마지막 방법으로 사용하게 될 부분이기 때문에 조금 코드가 길어보인다 하더라도 마지막 방법을 사용해주시는게 좋습니다.

한 가지 의문이 생길 수 있는 부분은

ul이나 div 같은 부모 요소가 없는 경우에는 어떻게 이벤트를 주느냐는 문제인데요

그것은 아래와 같이

$('document').on('click', 'div', function(){
	//실행 코드
});

 document를 대상으로 on이벤트를 주시면 됩니다.

그럼 오랜만에 돌아온 웹퍼블리싱 강좌 끝~

I have the following menu items generated by a template generator, artisteer:

<ul class="art-vmenu">

<li><a href="#" ><span class="l"></span><span class="r"></span>
        <span class="t">Home</span></a></li>    
<li><a href="#" ><span class="l"></span><span class="r"></span>
        <span class="t">Create User</span></a></li> 
<li><a href="#" class="active"><span class="l"></span><span class="r"></span>
        <span class="t">List Users</span></a></li>  
<li><a href="#"><span class="l"></span><span class="r"></span>
        <span class="t">Admin</span></a></li>   
</ul>

I want to capture the onclick event for <li> with a single jQuery function: I've tried this which is incomplete:

$(document).ready(function() 
{
   $('ul.art-vmenu li').click(function(e) 
   { 
    alert(this);
   });
});

I can go as far as seeing this is a HTMLliElement but cannot figure how to get the menu text or id for it?

How is menu click usually captured with jQuery?

JQuery li click 이벤트 - jQuery li click ibenteu

wonea

4,55317 gold badges83 silver badges137 bronze badges

asked Jun 15, 2011 at 22:36

Here, to get the text of the menu that triggered the event (does not seem to have any id):

 $(document).ready(function() 
 {
    $('ul.art-vmenu li').click(function(e) 
    { 
     alert($(this).find("span.t").text());
    });
 });

answered Jun 15, 2011 at 22:43

LocksfreeLocksfree

2,66223 silver badges19 bronze badges

0

In your question it seems that you have span selector with given to every span a seperate class into ul li option and then you have many answers, i.e.

$(document).ready(function()
 {
   $('ul.art-vmenu li').click(function(e) 
    { 
     alert($(this).find("span.t").text());
   });
});

But you need not to use ul.art-vmenu li rather you can use direct ul with the use of on as used in below example :

$(document).ready(function()
 {
  $("ul.art-vmenu").on("click","li", function(){
     alert($(this).find("span.t").text());
  });
});

answered Oct 7, 2013 at 19:54

JQuery li click 이벤트 - jQuery li click ibenteu

Manoj SainiManoj Saini

3392 silver badges8 bronze badges

1

I'm not really sure what your question is, but to get the text of the li element you can use:

$(this).text();

And to get the id of an element you can use .attr('id');. Once you have a reference to the element you want (e.g. $(this)) you can perform any jQuery function on it.

answered Jun 15, 2011 at 22:39

James AllardiceJames Allardice

162k21 gold badges328 silver badges310 bronze badges

You can get the ID, or any other attribute, using jQuery's attrib function.

$('ul.art-vmenu li').attrib('id');

To get the menu text, which is in the t span, you can do this:

$('ul.art-vmenu li').children('span.t').html();

To change the HTML is just as easy:

$('ul.art-vmenu li').children('span.t').html("I'm different");

Of course, if you wanted to get all the span.t's in the first place, it would be simpler to do:

$('ul.art-vemnu li span.t').html();

But I'm assuming you've already got the li's, and want to use child() to find something within that element.

answered Jun 15, 2011 at 22:43

Typing in $(this) will return the jQuery element instead of the HTML Element. Then it just depends on what you want to do in the click event.

alert($(this));

answered Jun 15, 2011 at 22:39

CraigWCraigW

7054 silver badges5 bronze badges

1

this is a HTML element.
$(this) is a jQuery object that encapsulates the HTML element.

Use $(this).text() to retrieve the element's inner text.

I suggest you refer to the jQuery API documentation for further information.

answered Jun 15, 2011 at 22:42

Bertrand MarronBertrand Marron

20.9k8 gold badges54 silver badges92 bronze badges

$(document).ready(function() {
    $('ul.art-vmenu li').live("click", function() {
        alert($(this).text());
    });
});

jsfiddle: http://jsfiddle.net/ZpYSC/

jquery documentation on live(): http://api.jquery.com/live/

Description: Attach a handler to the event for all elements which match the current selector, now and in the future.

answered Jun 15, 2011 at 22:55

JQuery li click 이벤트 - jQuery li click ibenteu

jk.jk.

14.3k4 gold badges42 silver badges57 bronze badges