简体   繁体   中英

Returning DIV contents with jQuery

While this seems simple at first glance, I'm having trouble getting what I want. I have many DIVs on a page with the same class which I use to find their text contents:

var Name =  $(".class").text();

While this works, it returns all of the text from all DIVs on the page at once such as

Name1Name2Name3Name4Name5

I am calling this request from a jQuery onclick event that is inside one of these DIVs. So my goal is to get the contents of the DIV that the onclick was fired from, not everything. The end result would be if I press the onclick from Name 3 it would only get the contents for that DIV, thus giving me Name3 only.

The DIV does have a unique ID I can also check against but I can't figure out how to use that to my advantage. The DIV structure looks like:

<div id="2242yrcwrmz5t1zyt03" class="class1" tabindex="-1">

Thank you!

You can get the element you clicked by using $(this)

$(".class").click(function(){
   alert($(this).text());  
});

Your click event is bubbling up in the DOM hierarchy you need to stop that which could be done by using event.stopPropagation

$('.class1').click(function(event){
     alert($(this).text());
     event.stopPropagation();
});

So read the text from the current div with this

$(".class").on("click", function() {
    console.log($(this).text());
});

I believe you need to use the event.target property to find the element that you actually clicked on.

Assuming your DIV that contains Name1, Name2, etc. has the id outerElement :

$("#outerElement").on("click", function(e) {
  var Name =  $(e.target).text();
});

More info here: https://api.jquery.com/category/events/event-object/

如果单击div中的元素,则应使用

var name = $( this ).parent(".class").text();

you can use jQuery parent() method

$(this).parent().text()

heres jsfiddle example https://jsfiddle.net/c628Lwuq/

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