开发者

Parent element selection problem?

My HTML is something like this

<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

$(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


Try $(this).parent().attr('id');


You'd be better off using event delegation and only having one event handler on the parent <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. 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.

$(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
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜