我正在编写一个小脚本,我注意到一些有重复元素的东西。在这种情况下$('#theSelect1 ..')是重复的,我想避免它。
$('#theSelect1').change(function(){
//console.log ($(this));
console.log(
$("#theSelect1 option:selected").text() // is there a way to change #theSelect1 to be $(this) inside this statement? I try not to repeat things.
);
})
Run Code Online (Sandbox Code Playgroud)
这是 HTML
<select id="theSelect1">
<option value="foo" selected="selected">1</option>
<option value="bar">2</option>
<option value="foobar">3</option>
Run Code Online (Sandbox Code Playgroud)
谢谢
您可以执行以下操作:
$(this).children("option:selected").text();
Run Code Online (Sandbox Code Playgroud)
这将查看与您的选择器匹配的当前元素的子元素。这仅查看第一级后代,因此如果您想要任何后代,请使用以下内容:
$(this).find("option:selected").text();
Run Code Online (Sandbox Code Playgroud)