【问题标题】:Getting to know which child was clicked of a tag in jquery了解在 jquery 中单击了标签的哪个孩子
【发布时间】:2011-10-21 19:38:11
【问题描述】:

我有以下DOM结构,基于h4的点击,我需要获取相应类小部件的id并向服务器发出post请求。我对 jQuery 有点陌生,因此很挣扎。有人可以帮忙吗?

<section id="home-sidebar" class="sidebar">
  <div class="menu">

    <div class="widget" id="4">
      <div class="title">
        <h4>First Text</h4>
        <p>Do some stuff</p>
      </div>
    </div>
    ..................................
...............

    <div class="widget" id = "56">
      <div class="title">
        <h4>N-th Text</h4>
        <p>Do some stuff</p>
      </div>
    </div>
  </div>
</section>

我如何知道在 jQuery 中点击了哪个 h4 标签?我如何获得小部件的相应“id”编号? (注意 id 不是连续的,它们也可以是随机的)

【问题讨论】:

  • 数值不是 ID 属性的有效 W3 值。 ID 和 NAME 标记必须以字母 ([A-Za-z]) 开头,后跟任意数量的字母、数字 ([0-9])、连字符 ("-")、下划线 ("_") 、冒号 (":") 和句点 (".")。

标签: jquery dom jquery-selectors


【解决方案1】:

您可以使用.parents() 查找具有您要抓取的 id 的 DOM 节点:

//bind a click handler to all h4 elements
$('h4').bind('click', function () {
    //find the id of the parent node that has the .widget class
    //since you are trying to get the id, you do not need to use the jQuery .attr() function which performs slower than the below code
    var id = $(this).parents('.widget')[0].id;
    $.get('path/to/server.file?id=' + id, function (data) {
       //this is the callback function for the server request
       alert('Server Response: ' + data);
    });
});

.parents() 的文档:http://api.jquery.com/parents/

【讨论】:

    【解决方案2】:

    如果你这样做了:

    $('h4').click(....)
    

    你可以这样做:

    $('h4').click(function(){
        alert($(this).attr('id'))
    })
    

    【讨论】:

      【解决方案3】:
      $("h4").click(function(){  
          var  a=$(this).parent().parent().attr('id');  
          alert(a);  
      })
      

      【讨论】:

        【解决方案4】:
        $(document).ready(function(){ 
            $(".widget").click(function(){
                var id = $(this).attr("id");  //gives id
            });
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-01-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多