简体   繁体   中英

How to get descendant span element with jQuery?

I have the following HTML:

<a href="javascript:search_rate(this, 'key', 'upvote', 'url' );">
    <div>
        <span class="glyphicon glyphicon-thumbs-up"></span> <span class="rating">0</span>
    </div>
</a>

In the function search_rate, I would like to use the this variable that I passed to get the element with class="rating" and then update its value from 0 to 1. I am using jQuery and I wrote the following to try to get the element:

update_node = $(this).find('.rating');

However, for some reason update_node does not point to the correct DOM element. Just to clarify I am a beginner and have been struggling with how to use jQuery to navigate the DOM. Help is greatly appreciated, thanks!

If you're going to use jQuery you don't need to pass a function through href . You don't need to use an a tag at all. Just target the div clicked and update its child .rating

HTML

<div class="upvote">
    <span class="glyphicon glyphicon-thumbs-up"></span> 
    <span class="rating">0</span>
</div>

JS

$(".upvote").click(function(){
   $(this).find(".rating").html("1");    
});

EXAMPLE 1

NOTE: if you're looking to do an upvote count system, I would pull the number on page load and add 1 to it on click:

//pull current number
var currentCount = $(".upvote .rating").text();

$(".upvote").click(function(){ 
  $(this).find(".rating").html(parseInt(currentCount)+1); 
});

EXAMPLE 2

UPDATE

To pass other values to the click event, just add them as data attributes:

<div class="upvote" data-one="hello" data-two="goodbye">

EXAMPLE 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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