Some confusion in the use of jquery indexes
- 2020-03-26 21:38:02
- OfStack
Today, my colleague posed two questions about jquery to me in a very formal way. I also answered them in a very formal way. By the way, I posted the source code here in the hope of helping my friends:
Problem a: Why now pop out each button (in ul> The index value of) in li is zero, why not from 0 to 9;
Answer: the index of the first matched element, relative to its sibling, gets the index position of the first matched element relative to its sibling. "Compatriots," please.
Problem two: Why not ul> in button; In li, and after each button add < Br / > The index value of the popup button is doubled from 0 to 18.
Answer: because < Br / > It's also a sibling element.
The following is the meaning of "compatriots" found in baidu baike:
A sibling, such as a sibling;
<script type="text/javascript">
$(function(){
$("input[type=button]").click(function(){
alert($(this).index());
})
})
</script>
<ul>
<li><input type="button" value=" Button a " /></li>
<li><input type="button" value=" Button a " /></li>
<li><input type="button" value=" Button a " /></li>
<li><input type="button" value=" Button a " /></li>
<li><input type="button" value=" Button a " /></li>
<li><input type="button" value=" Button a " /></li>
<li><input type="button" value=" Button a " /></li>
<li><input type="button" value=" Button a " /></li>
<li><input type="button" value=" Button a " /></li>
<li><input type="button" value=" Button a " /></li>
</ul>
Problem a: Why now pop out each button (in ul> The index value of) in li is zero, why not from 0 to 9;
Answer: the index of the first matched element, relative to its sibling, gets the index position of the first matched element relative to its sibling. "Compatriots," please.
<script type="text/javascript">
$(function(){
$("input[type=button]").click(function(){
alert($(this).index());
})
})
</script>
<ul>
<input type="button" value=" Button a " /><br />
<input type="button" value=" Button a " /><br />
<input type="button" value=" Button a " /><br />
<input type="button" value=" Button a " /><br />
<input type="button" value=" Button a " /><br />
<input type="button" value=" Button a " /><br />
<input type="button" value=" Button a " /><br />
<input type="button" value=" Button a " /><br />
<input type="button" value=" Button a " /><br />
<input type="button" value=" Button a " /><br />
</ul>
Problem two: Why not ul> in button; In li, and after each button add < Br / > The index value of the popup button is doubled from 0 to 18.
Answer: because < Br / > It's also a sibling element.
The following is the meaning of "compatriots" found in baidu baike:
A sibling, such as a sibling;