在find命令中使用字符串

时间:2014-02-11 22:47:58

标签: jquery

我使用Jquery来显示一些元素,并尝试对失败的for语句执行相同的操作。

现有工作代码

$( this ).closest('table').find('#DISPLAYIP').html("Validated").show()
$(this).closest('table').find('#DISPLAYDNS1').html("Validated").show()
$( this ).closest('table').find('#DISPLAYDNS2').html("Validated").show()
$( this ).closest('table').find('#DISPLAYGW').html("Validated").show()
$( this ).closest('table').find('#DISPLAYNM').html("Validated").show()
$( this ).closest('table').find('#DISPLAYNTP1').html("Validated").show()
$( this ).closest('table').find('#DISPLAYNTP2').html("Validated").show()
$( this ).closest('table').find('#DISPLAYHOST').html("Validated").show()
$( this ).closest('table').find('#DISPLAYID1').html("Validated").show()

新代码无效

displayfields = ['#DISPLAYIP','#DISPLAYDNS1','#DISPLAYDNS2','#DISPLAYGW','#DISPLAYNM','#DISPLAYNTP1','#DISPLAYNTP2','#DISPLAYHOST','#DISPLAYID1']

    displayfields.forEach(function(i){
                                alert("displayfields = " + i)
                                $( this ).closest('table').find(i).html("Validated").show()
                                alert("Over" )

                            })

4 个答案:

答案 0 :(得分:0)

for (var i = 0; i < displayfields.length; i++) {
    $( this ).closest('table').find(displayfields[i]).html("Validated").show()
}

不要使用for a for迭代数组,因为您将迭代所有Object属性。不保证Object属性迭代的顺序,可能不会以数字顺序访问数组索引。还枚举了Object的继承属性。

答案 1 :(得分:0)

在您的代码中不确定这一点,但我们假设它是jquery小部件,例如,如果是这样的话:

var cachedTable =  $(this).closest('table');
    displayfields.forEach(function(i){
        console.log("displayfields = " + i);
        cachedTable.find(i).html("Validated").show();
    });
    console.log('done');

As +如果您尝试更新的所有内容都位于逻辑区域,只需为其创建模板,然后构建html,然后进行更新。它将极大地减少DOM调用,而不是ID数组的长度

答案 2 :(得分:0)

由于id在文档中是唯一的,为什么不简单:

$(displayFields.join(',')).html('validated').show();

如果你真的想使用原生的forEach,我建议:

displayFields.forEach(function(id){
    $(id).html('validated').show();
});

但是混合DOM和jQuery是不必要的,并且使用兼容的浏览器可以使用本机DOM:

displayFields.forEach(function(id){
    var elem = document.querySelector(id);
    elem.innerHTML = 'validated';
    elem.style.display = 'block';
});

答案 3 :(得分:0)

假设你有$(this)的有效元素,你可以使用每个jquerys来做到这一点非常简单,但你需要引用它来维持范围。

var that = $(this);
$.each(displayfields, function(i, e){
   that.closest('table').find(displayfields[i]).html("Validated").show();
});