捕获`span`标签上的onClick事件

4

我的 div 元素里有很多 span 标签。每个 div 都有一个唯一的 id。我想为每个 div 中的 span 元素添加单击事件,使其独立响应。如何实现?

  <div class="bootstrap-tagsinput"id="1">
  <span class="tag label label-info">Access control lists</span> 
  <span class="tag label label-info">Network firewall</span> 
  </div>


  <div class="bootstrap-tagsinput"id="2">
  <span class="tag label label-info">Access control lists</span> 
  <span class="tag label label-info">Network firewall</span> 
  </div>

我的当前脚本可以捕获所有的span元素,无论它们在哪个div中。

      $('span.label-info').click(function() {

         var news=$('input[type=text][id="vuln<?php echo $model->v_id;?>"]').val()+','+$(this).text();
         $('input[type=text][id="vuln<?php echo $model->v_id;?>"]').val(news);
        return false;
});

我该怎样分别捕获每个 div 内的 span 元素的点击事件?

1
$('#1 span').click(.., $('#2 span').click(.. 等等。但是你为什么要这样做呢? - user3559349
问题是我有很多标签在表格中,我只想根据标签点击更新相应的<td>。每一行对应一个对象,因此id是对象的id。 - Dency G B
我正在使用for循环来创建我的表格行。 - Dency G B
因此,只需为所有跨度使用一个单击处理程序,然后获取其父td元素 $('span.label-info').click(function() { var cell = $(this).closest('td');.... - user3559349
由于您正在动态创建表格,因此应该是$('#mytable').on('click', 'span.label-info', function() {... - user3559349
3个回答

1

我认为你的看法有误。不需要为每个div单独编写点击处理程序,而是可以保留共享的点击处理程序,然后找出其父级div,并在随后的选择器中使用其ID。

$('span.label-info').click(function() {

    // find the parent/ansector that is a div and has the class
    var divId = $(this).closest('div.bootstrap-tagsinput').prop('id');

    var news=$('input[type=text][id="vuln' + divId + '"]').val()+','+$(this).text();
    $('input[type=text][id="vuln' + divId + '"]').val(news);
    return false;
});

0

你的代码应该能够为每个元素添加点击事件处理程序。

$('span.label-info').click(function() {
    $(this).attr('id'); //<--$(this) is a handle to the clicked span
    $(this).parent().attr('id'); //<-- $(this).parent() references the parent div
});

值得一提的是,考虑将.click()更改为.on('click')
此外 - 如果您想要在动态添加到div后不需要重新绑定就能绑定一次,可以像这样绑定:
$('div').on('click', 'span.label-info').click(function() {  
   /* <-- do stuff with $(this) or $(this).parent() here --> */
});

0

http://jsfiddle.net/GZVdL/3/

你好。

在你的 span 点击事件中,你可以找到父 div,然后获取它的属性 id 来确定它是哪个 div。 以下是代码:

$(document).ready(function(){


$(".tag").click(function(){


    alert($(this).parent().attr("id"));
});

}); 

谢谢。但是我该如何获取那个 span 值并更新两个 div 之间的另一个 div(它不是父 div)? - Dency G B
请在您想要更新的<span> divID </span>中自定义标签,检查我已经相应更改了它:http://jsfiddle.net/GZVdL/5/ - Megha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接