1

我确信有一个简单的解决方案。

开始的场景如下。我创建一个<select>元素并动态填充它:

function CreateDropDown(name, id, optionList)
{
    var combo = $("<select></select>").attr("id", id).attr("name", name);

    $.each(optionList, function (i, item) {
        combo.append("<option value='"+item.val+"'>" + item.el + "</option>");
    });

    return combo;
}

目的是提取outerHTML。以下工作正常:

combo[0].outerHTML();

但我觉得索引数组非常粗糙。至少在 jQuery() 函数返回单个元素数组的所有情况下。

问题

每当 jQuery() 函数返回单个元素数组时,是否可以在没有数组索引的情况下获取唯一元素?

演示

4

3 回答 3

3

jQuery objects are inherently collections of DOM objects, and there is no syntactic way to treat a jQuery object as wrapper around a single item.

jQuery documentation suggests using get method to access individual DOM elements. It does not comment on performance difference between indexing operator and .get(), but it does say that "each jQuery object also masquerades as an array", so it would be ok to assume that indexing operator just adds another method call.

于 2012-11-09T15:34:21.390 回答
2

如果您“觉得索引数组非常粗糙”,您可以编写自己的帮手方法。像这样的东西:

window.$$ = function(){
   return jQuery.apply(jQuery,arguments)[0];
}

用法:

var combo = $$("<select></select>");
console.log( combo.outerHTML );
于 2012-11-09T15:46:24.180 回答
1

Use .get() to get the html elements.

http://api.jquery.com/get/

于 2012-11-09T15:34:20.030 回答