[英]How to avoid repetition of selector names in jQuery?
我是jQuery和Javascript的新手,我想知道是否有较短的方法可以编写此代码:
function setSearchForm() {
if ($('#search input[type=text]').val().length != 0) {
$('#search input[type=submit]').removeProp('disabled');
$('#search #clear_button').show();
} else {
$('#search input[type=submit]').prop('disabled', true);
$('#search #clear_button').hide();
}
}
#search
选择器的重复令我感到笨拙。
谢谢你的帮助。
可能有:
function setSearchForm() {
var s = $('#search'), l = !$('input[type=text]',s).val().length;
$('input[type=submit]',s).prop('disabled',l)
$('#clear_button',s).toggle(!l);
}
一件事是,由于#clear_button
已经具有ID,因此您无需在其中引用#search
。 因此,这里有一个快速的代码清理:
function setSearchForm() {
if ($('#search input[type=text]').val().length != 0) {
$('#search input[type=submit]').removeProp('disabled');
$('#clear_button').show();
} else {
$('#search input[type=submit]').prop('disabled', true);
$('#clear_button').hide();
}
}
我认为您不应该使用removeProp
,删除元素的属性会导致不良行为。 但是对于您的问题,您可以将其编写为:
var $search = $('#search');
function setSearchForm() {
$search.find('#clear_button').toggle();
$search.find('input[type=submit]').prop('disabled', !$search.find('input[type=text]').val().length);
}
只需使用prop并将标志设置为禁用即可。 摘自官方文件
使用DOM元素或窗口对象的某些内置属性,如果尝试删除该属性,浏览器可能会生成错误。 jQuery首先将未定义的值分配给属性,并忽略浏览器生成的任何错误。 通常,仅需要删除已在对象上设置的自定义属性,而不是内置(本机)属性。
注意:请勿使用此方法删除本机属性,例如选中,禁用或选中。 这将完全删除该属性,并且一旦删除,就不能再次将其添加到element中。 使用.prop()将这些属性设置为false。
由于您使用的是ID并且必须是唯一的,因此您也可以这样做
//cache this outside since this is gng to be unique and to avoid creating the object over and again
var $search = $('#search'), $clear = $('#clear_button');
function setSearchForm() {
$clear.toggle();
$search.find('input[type=submit]').prop('disabled', !$search.find('input[type=text]').val().length);
}
将选择器分配给变量,即缓存选择器,并在需要的地方使用它。
var s_s = $('#search input[type=submit]');
var s_t = $('#search input[type=text]');
var s_c = $('#search #clear_button');
function setSearchForm() {
s_s.prop('disabled', !s_t.val().length);
s_c.toggle();
}
$(document).ready(function(){
var search = $('#search'),
submit = search.find('input[type=submit]'),
textInput = search.find('input[type=text]'),
clear = $('#clear_button');
setSearchForm = function(){
if (textInput.val().length != 0) {
submit.removeProp('disabled');
clear.show();
} else {
submit.prop('disabled', true);
clear.hide();
}
}
});
尽管我建议您不要使用setSearchForm
函数污染全局名称空间
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.