I want to get the value of an id from a nested div - jquery
I want to obtain the .text() of #inner2
<div class="outer" id="outer">
<div id="inner1开发者_JAVA技巧" class="inner">test1</div>
<div id="inner2" class="inner">test2</div>
<div id="inner3" class="inner">test3</div>
</div>
This is the jquery function I am using
$('.outer').bind('click',function() {
var one = $('#inner'+x).attr('id');
alert(one);
});
The problem is the first #id value is show in the alert.
Thanks
Jean
You can use .each
to iterate through the divs with class name inner and then fetch the ids.
$('.outer').bind('click',function() {
$("div.inner").each(function(){
alert ($(this).attr("id"));
});
});
If you want the id of the clicked one then use event.target
like
$('.outer').bind('click',function(e) {
alert (e.target.id);
alert($(e.target).text());
// to get text wrap e.target to a jquery object and use .text() on that
});
$('.outer').bind('click',function() {
var one = $('#inner2').attr('id');
alert(one);
$('.outer').bind('click',function() {
var one = $('#inner2').text();
alert(one);
});
If it's just to retrieve the inner2 on click:
$("#outer").click(function() {
alert($("#inner2").text());
});
But if you actually are trying to get the text of the clicked inner div, then the following code will work:
$("#outer .inner").click(function() {
alert($(this).text());
});
If it's to retrieve the ID, then just change text()
to attr('id')
.
精彩评论