简体   繁体   English

使用jQuery .attr()方法获取元素属性

[英]Getting element attribute with jQuery .attr() method

I'm using jQuery .attr() method to get the value of an element's attribute, in this case an id, and storing it into a string. 我正在使用jQuery .attr()方法来获取元素属性的值(在本例中为id),并将其存储到字符串中。 Then I replace "info" to "article" in the string to hide and show elements in my page. 然后,我将字符串中的“ info”替换为“ article”,以隐藏和显示页面中的元素。

My HTML code looks like this: 我的HTML代码如下所示:

<div id="navigator">
    <div id="info_01"><a href="#">Lorem Ipsum</a>
        <div id="info_02"><a href="#">Lorem Ipsum</a></div>
    </div>
    <div id="info_03"><a href="#">Lorem Ipsum</a></div>
</div>

jQuery code: jQuery代码:

    $('#navigator>div, #navigator>div>div').click(function(){
    var variable=$(this).attr('id');
    var variable2=(variable.replace("info", "article"));
    console.log(variable2);

    $("#another_div").hide();
    $("#"+variable2).show();
});

I'm outputting log to console, and when I click on parent divs inside #navigator such as #info_01 and #info_03 it prints only the id of the div I clicked, but when I click on child elements in #navigator such as #info_02 , it prints two lines: 我正在将日志输出到控制台,并且当我单击#navigator父div(例如#info_01#info_03它仅打印我单击的div的ID,但是当我单击#navigator子元素(例如#info_02 ,它打印两行:

article_02
article_01

As you can see, the first one is from the first div I click on, but since I'm also clicking on its parent, it outputs the parent's id. 如您所见,第一个是我单击的第一个div,但是由于我也在单击其父级,因此它会输出父级的ID。

I only need to output one id, the one from the element I click on, and not its parent's id. 我只需要输出一个id,即我单击的元素中的一个id,而不是其父级的id。

How can I do that? 我怎样才能做到这一点?

Use .stopPropagation() . 使用.stopPropagation() This prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. 这样可以防止事件使DOM树冒泡,从而防止任何父处理程序收到该事件的通知。 Read more on https://api.jquery.com/event.stoppropagation 进一步了解https://api.jquery.com/event.stoppropagation

$('#navigator>div, #navigator>div>div').click(function(e){
    var variable=$(this).attr('id');
    var variable2=(variable.replace("info", "article"));
    console.log(variable2);

    $("#another_div").hide();
    $("#"+variable2).show();
    // propagate
    e.stopPropagation();
});

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

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