我正在尝试创建一个带有两个参数的函数。第一个是父母元素,第二个是排除的元素。该函数应该重置所有子元素,但第二个参数中发送的元素列表除外,并且不应该重置。我已经按照下面的方法使用选择器取得了一些成功。现在我有两个查询
function resetdetaildata(parentselector, elem) {
var $self = $(parentselector);
if(elem == '')
{
$($self).children().find('input').val("");
$($self).children().find('select').each(function () {
$(this).find('option:gt(0)').remove();
$(this).find('option:first').prop('selected', true);
});
}
else
{
alert(parentselector);
$($self).children('input:not(' + elem + ')').find('input').val("");
$($self).children('select:not(' + elem + ')').find('select').each(function () {
$(this).find('option:gt(0)').remove();
$(this).find('option:first').prop('selected', true);
});
}
}
目前,我正在这样调用此方法
resetdetaildata('#Parent', '.clsmaterial');
答案 0 :(得分:1)
您不想在进行find
调用后再进行children
调用。 find
在集合中的元素中内部,但是input
元素永远不能在其他input
元素之内,并且select
元素永远不能在该元素之内其他select
个元素。
另外,您永远不想在jQuery集($()
)上使用$($self)
。
我可能会先找到所有input
和selects
,然后在elem
正确的情况下使用.not()
删除我不想匹配的内容
function resetdetaildata(parentselector, elem) {
var $self = $(parentselector);
// Find all inputs and selects
var $inputs = $self.find('input');
var $selects = $self.find('select');
if (elem)
{
// We're filtering, so do that
$inputs = $inputs.not(elem);
$selects = $selets.not(elem);
}
$inputs.val("");
$selects.each(function () {
$(this).find('option:gt(0)').remove();
$(this).find('option:first').prop('selected', true);
});
}
旁注:通过直接使用DOM,可以使option
中除第一个select
之外的所有代码变得更简单:
function resetdetaildata(parentselector, elem) {
var $self = $(parentselector);
// Find all inputs and selects
var $inputs = $self.find('input');
var $selects = $self.find('select');
if (elem)
{
// We're filtering, so do that
$inputs = $inputs.not(elem);
$selects = $selets.not(elem);
}
$inputs.val("");
$selects.each(function () {
this.options.length = 1; // <== Removes all options except the first
this.selectedIndex = 0; // <== Selects the first option
});
}