我有 5 个完全相同的div,在每个div 中我都有一个选择选项输入.. 所有div 都有相同的 id,所以我想获取最近的div 选择,然后在里面做 innerHTML。
所以我想要这样的东西:
$(this).closest('div[maybeidhere?]').innerhtml ='whole content here';
提前致谢
编辑:忽略相同的id,假设所有ID都有相同的类
<div>
<select id="faculty" onchange="inchange(this)">
<option value="fos">Faculty of Science</option>
<option value="fot">Faculty of Information Technology</option>
<option value="foe">Faculty of Engineering</option>
<option value="other">Other</option>
</select>
<div class="degreediv"></div>
</div>
<script>
function inchange(input){
if($(input).val()=="fot"){
$(this).closest('div[.degreediv]').innerhtml ='FOT CONTENT';
}
else if($(input).val()=="fos"){
$(this).closest('div[.degreediv]').innerhtml ='FOS CONTENT';
}
else if($(input).val()=="foe"){
$(this).closest('div[.degreediv]').innerhtml ='FOE CONTENT';
}
else if($(input).val()=="other"){
$(this).closest('div[.degreediv]').innerhtml ='other CONTENT';
}
};
</script>
由于 select 在div 内部,因此您可以使用 .父(( 函数
$(this(.parent((.innerhtml;
<select>
<option value="value1">1</option>
<option value="value2">2</option>
<option value="value3">3</option>
</select>
<div>this is div 1</div>
<div>this is div 2</div>
...
<div>this is div n</div>
如果您的代码类似于以下内容,则:
$textOfDiv = $('select + div').val(); // selects text inside first DIV element
或
$htmlOfDiv = $('select + div').html(); // selects html inside first DIV element
请注意,jQuery
选择器的工作方式与CSS
选择器类似。
指:
CSS Selector Reference
https://www.w3schools.com/cssref/css_selectors.asp
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors
jQuery Selector Reference
https://api.jquery.com/category/selectors/