gpt4 book ai didi

javascript - 为父项重置选定的子项

转载 作者:行者123 更新时间:2023-12-01 04:34:22 26 4
gpt4 key购买 nike

我正在尝试创建一个带有两个参数的函数。第一个是父元素,第二个是排除元素。该函数应该重置除第二个参数中发送的要排除的元素列表之外的所有子元素,并且不应重置。我按照下面的方法使用选择器取得了一些成功。现在我有两个疑问

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');
  • 如何将参数从选择器更改为元素。
  • 将第二个参数作为数组并从代码中调用

最佳答案

您不想在执行 children 调用后执行 find 调用。 find 在集合中的元素查找,但 input 元素永远不能在其他 input 元素内,并且 select 元素永远不能位于其他 select 元素内。

另外,您永远不想在 jQuery 集 ($($self)) 上使用 $()

我可能会首先找到所有的inputselects,然后使用 .not()如果 elem 为真,则删除我不想匹配的内容。

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 来简化代码,删除 select 中除第一个 option 之外的所有内容:

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
});
}

关于javascript - 为父项重置选定的子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59810002/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com