jquery: get value from clicked div

前端 未结 2 989
太阳男子
太阳男子 2021-02-06 08:33
\'.$i.\'

$i is auto generated by loop - which could lead to:

\'.$i.\'
\'.$i.\
2条回答
  •  無奈伤痛
    2021-02-06 09:26

    If you don't have any other way to identify the

    elements, this would place a handler on every
    on the page.

    $('div').click(function() {
        var text = $(this).text();
        // do something with the text
    });
    

    The .text() method will return the text content for that

    , (as well as any nested elements).

    If you only wanted the click event on certain

    elements, the best is to add a class, and select the correct ones based on that.

    $('div.myClass').click(function() {
        var text = $(this).text();
        // do something with the text
    });
    

    HTML

    '.$i.'
    '.$i.'
    '.$i.'
    some other div

    If the

    elements are all within the same ancestor element, you could use .delegate() instead, which will place one handler on the ancestor to handle all divs inside.

    $('#parentID').delegate('div.myClass', 'click', function() {
        var text = $(this).text();
        // do something with the text
    });
    

    HTML

    '.$i.'
    '.$i.'
    '.$i.'

    (Requires jQuery 1.4 or later)

提交回复
热议问题