为什么 jquery 父子选择器在这里不起作用。
这里的article元素有它的子元素部分,并且部分包含html select
标签。
所以,对于父子逻辑,它必须起作用,不是吗?它返回未定义。
$(document).on('change', 'select[name="slct_sec"]', function(){
//This one is working
var cls=$('section > select[name="slct_cls"]').val();
//Not working
var cls_1=$(this).parent('section').siblings('section > select[name="slct_cls"]').val();
//Not working
var cls_2=$(this).parent('article').children('section > select[name="slct_cls"]').val();
alert(cls_1);
alert(cls_2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<article>
<section>
<select name='slct_cls'>
<option value='1'>One</option>
<option value='2'>Two</option>
</select>
</section>
<br/>
<section>
<select name='slct_sec'>
<option value='1'>A</option>
<option value='2'>B</option>
</select>
</section>
</article>
</body>
</html>
最佳答案
您不知道与要定位的元素对应的部分
,即带有select[name="slct_cls"]
的部分,因此您无法use siblings
- 对于 sibling ,您希望选择带有 slct_cls
的 sibling ,但您事先不知道哪个 sibling 具有该属性。最好上一层,到 article
,并使用 .find
查找具有该选择器的后代元素:
$(document).on('change', 'select[name="slct_sec"]', function() {
var cls_1 = $(this).closest('article').find('select[name="slct_cls"]').val();
console.log(cls_1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<article>
<section>
<select name='slct_cls'>
<option value='1'>One</option>
<option value='2'>Two</option>
</select>
</section>
<br/>
<section>
<select name='slct_sec'>
<option value='1'>A</option>
<option value='2'>B</option>
</select>
</section>
</article>
</body>
</html>
关于javascript - jquery父子选择器返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52361351/