问题
Starting from a particular div
I want to use jquery to grab the value of the input
tag in the next div
block (two levels down). I have an HTML structure like this:
<div class="firstClass1" id="firstID1"> // suppose I start from this element
<div class="secondClass1" id="secondID1">
<input value="myValue1"/>
</div>
</div>
<div class="firstClass2" id="firstID2">
<div class="secondClass2" id="secondID2">
<input value="myValue2"/>
</div>
</div>
<div class="firstClass3" id="firstID3">
<div class="secondClass3" id="secondID3">
<input value="myValue3"/>
</div>
</div>
...
That is, if I start from .firstClass1
, I want to get the value from myValue2
. I have tried using the following jquery, but it doesn't work:
var nextID = $('.div#firstID1').next().find('input').val();
and
var nextID = $('.div#firstID1').next().next().val();
回答1:
you have missed a quotation mark, also remove the dot
from .div#firstID1
:
var nextID = $('div#firstID').next().find('input').val();
回答2:
This will help : http://jsfiddle.net/bQYZJ/
You had extra .
dot as well as id
was firstID1
not firstID
:)
Rest I have tuned it for your need.
Hope this help,
code
var nextID = $('div#firstID1').next('div').find('input').val();
回答3:
Replace the .div
with just div
.
Just try with:
$('div[id^=firstID]').mouseenter(function(){
var nextID = $(this).next().find('input').prop('value');
alert( nextID ); // test it!
});
$('div[id^=firstID]')
means "any div which ID starts with firstID
",
this will allow you to grab the 'next div input value' of any 'evented' element so you don't need to rewrite the code for ANY firstID[N]
element.
回答4:
You can also use,
var nextID = $('div#firstID1 > div > input')
or
var nextID = $('div#firstID1').children().children()
or
var nextID = $('div#firstID1').children('div').children('input');
But (for reasons unknown to me), find
works faster than children
and >
approach.
来源:https://stackoverflow.com/questions/11386628/how-can-i-use-jquery-to-get-the-value-of-a-child-of-a-child-that-is-in-an-adjace