开发者

How can I use jQuery to select and act on an element without a guard clause?

I am rewriting some old JavaScript with jQuery and would like to know how to write it more cleanly.

The script I'm starting with is:

for (var i = 0; i < form1.elements.length; i++) {
    var element = form1.elements[i];
    alert(element.id)

    if (Left(element.id, 15) === 'selHeaderFilter' || 
        element.id === 'ddlHierarchy1') {
        garrHeaderState[element.id] = element.selectedIndex
    }
}

I'm not really sure why it's been written as it was, but I think it is simply trying to add 2 elements to an array (that's declared globally).

My first stab at this has given me:

var hierarchy = $('[id$=ddlHierarchy1]');
var headerFilter = $('[id*="selHeaderFilter"]');

if (hierarchy)
    garrHeaderState[hierarchy.attr('id')] = hierarchy.val();

if (hea开发者_如何学运维derFilter)
    garrHeaderState[headerFilter.attr('id')] = headerFilter.val();

But I don't really like the process of declaring hierarchy just so that if it exists I can add its selected index to the array. Is there a better way of writing this code?


You could use the each function of jQuery.

$('[id$=ddlHierarchy1], [id*="selHeaderFilter"]').each(function(){
    var item = $(this);
    garrHeaderState[item.attr('id')] = item.val();
});


Untested:

$('[id$=ddlHierarchy1], [id*="selHeaderFilter"]').each(function(){
    garrHeaderState[this.id] = $(this).val();
})

Edit: updated according to edits from other post to avoid caching and duplicate running of jQuery function

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜