简体   繁体   English

父元素选择问题?

[英]Parent element selection problem?

My HTML is something like this 我的HTML是这样的

<div id="mydiv" class="common">
      <input type="text" id="text1" value="" />
      <input type="text" id="text2" value="" />
</div>

I am assigning a function on the onclick event of the textbox like this 我在像这样的文本框的onclick事件上分配一个函数

$(document).ready(function() {
      $(".common input").click(function() {

          //////// What I am trying to do is access the id of its parent 
                // in this case it is "mydiv"
          alert($(this:parent).attr('id'));
});

But it is not working 但这不起作用

尝试$(this).parent().attr('id');

You'd be better off using event delegation and only having one event handler on the parent <div> . 您最好使用事件委托,并且在父<div>上仅具有一个事件处理程序。 This will be more efficient by reducing the number of event handlers required, and by replacing the descendant and element selector with the much simpler and faster ID selector. 通过减少所需的事件处理程序数量,并用更简单,更快速的ID选择器替换后代和元素选择器,可以提高效率。 Also, within the event handler function you automatically have references to both elements you're interested in (via evt.target and this ) without having to do any traversal. 此外,在事件处理程序函数中,您可以自动引用对您感兴趣的两个元素(通过evt.targetthis ),而无需进行任何遍历。

$(document).ready(function() {
    $("#mydiv").click(function(evt) {
         if (evt.target.tagName.toLowerCase() == "input") {
             alert("Clicked input with ID " + evt.target.id);
             alert("Parent ID: " + this.id);
         }
     });
});

Change it to the following 将其更改为以下内容

$(document).ready(function() {
      $(".common input").click(function() {

        var divId =  $(this).parent().attr('id'));
        alert(divId);
});
$(document).ready(function() {
    $(".common input").click(function() {
        alert( $(this).parent().attr('id') ); // <- Use $(this).parent()
    }); // <- don't forget to close this function too
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM