Álv*_*lez 3 html javascript jquery
当我使用jQuery处理HTML表单元素时,我总是最终得到jQuery语法和普通JavaScript的丑陋混合,例如:
function doStuff($combo){
if( $combo.get(0).options[$combo.get(0).selectedIndex].value=="" ){
var txt = "";
}else{
var txt = $combo.get(0).options[$combo.get(0).selectedIndex].text;
}
var $description = $combo.closest("div.item").find("input[name$=\[description\]]");
$description.val(txt);
}
Run Code Online (Sandbox Code Playgroud)
是否有标准的jQuery的方法来处理像元素的典型操作<select>,<input type="radio">和<input type="checkbox">?
与典型的,我的意思是这样的东西读取选定的单选按钮的值的组中或在选择列表中替换元素.我没有在文档中找到它们,但我承认方法重载可能会使doc浏览器变得棘手.
感谢大家.一旦进入正确的轨道,我自己想出了剩下的东西.例如,我可以<select>像任何其他DOM树一样处理列表:
$("select")
.empty()
.append('<option value="">(Pick one)</option><option value="a">Option A</option><option value="b">Option B</option>');
Run Code Online (Sandbox Code Playgroud)
是的,您应该能够简化代码.以下是使用表单元素的几个示例:
<input type="text">$(':text') // select all text boxes
$('input#example').val(); // gets value of a text box
Run Code Online (Sandbox Code Playgroud)
<input type="checkbox">$(':checkbox') // selects all checkboxes
$('input.example:checked') // selects all ticked checkboxes with class 'example'
$('#example').is(':checked'); // true if checkbox with ID 'example' is ticked
Run Code Online (Sandbox Code Playgroud)
<input type="radio">$(':radio') // selects all radio buttons
$(':radio:checked').each( function() {
$(this).val(); // gets value of each selected radio button
});
$('input:radio[name="asdf"]'); // gets particular group of radio buttons
Run Code Online (Sandbox Code Playgroud)
<select>$('select#example').change( function() {
// this part runs every time the drop down is changed
$(this).val(); // gets the selected value
});
Run Code Online (Sandbox Code Playgroud)
有关更多选择器,另请参阅http://api.jquery.com/category/selectors/form-selectors/.
既然你想要文本而不是值,那么使用.text()它<option>(使用:selected选择器找到它),如下所示:
function doStuff($combo){
var txt = $combo.children("option:selected").text();
$combo.closest("div.item").find("input[name$=\[description\]]").val(txt);
}
Run Code Online (Sandbox Code Playgroud)
如果你想要值的一部分<option value="4" selected>Four</option>那么你可以使用.val(),如下所示:
var val = $combo.val();
Run Code Online (Sandbox Code Playgroud)