为父母重设孩子

时间:2020-01-19 12:27:46

标签: javascript jquery

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

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

1 个答案:

答案 0 :(得分:1)

您不想在进行find调用后再进行children调用。 find在集合中的元素中内部,但是input元素永远不能在其他input元素之内,并且select元素永远不能在该元素之内其他select个元素。

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

我可能会先找到所有inputselects,然后在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
    });
}
相关问题