$() 在 Internet Explorer 中的工作方式是否不同?
Does $() work differently in Internet Explorer?
我在 Firefox Developer Edition 38 和 Internet Explorer 8 和 9 中 运行 以下 JavaScript。
console.log('+++++++++++++++++++++++++++++++');
console.log('jquery version = ' + $.fn.jquery);
var myHtmlString = "<!-- my comment -->" +
"<optgroup label='my label'>" +
"<option value='1'>option one</option>" +
"</optgroup>";
console.log($(myHtmlString));
console.log($(myHtmlString)[0]);
console.log($(myHtmlString)[1]);
console.log($(myHtmlString).length);
在 Firefox 中,我得到:
在 IE 中,我得到:
因此,显然在 Firefox 中,一个 HTML 注释被添加为该对象的一个元素,但在 IE 中,它不是。为什么会这样,是否存在错误,或者我应该以其他方式创建此对象吗?
注意:我试过 $.parseHTML(myHtmlString)
但它做同样的事情。
更新:这个答案 How does jQuery treat comment elements? 提供了一个潜在的解决方法。
所以这取决于您使用的浏览器,但由于您传递的只是 1 个以上的简单标记,(例如 $('<div>example html creation</div>')
)jQuery 让 浏览器处理创建。
If the HTML is more complex than a single tag without attributes, as it is in the above example, the actual creation of the elements is handled by the browser's .innerHTML mechanism. In most cases, jQuery creates a new element and sets the innerHTML property of the element to the HTML snippet that was passed in.
例如,Firefox 正在查看您的每个 < >
区域,并找到 2 个。而 IE 不关心,并将其全部处理为 1(因此长度为 1)。
长话短说,你做得很好。这只是浏览器内部处理它的方式,您不必担心这些!
我在 Firefox Developer Edition 38 和 Internet Explorer 8 和 9 中 运行 以下 JavaScript。
console.log('+++++++++++++++++++++++++++++++');
console.log('jquery version = ' + $.fn.jquery);
var myHtmlString = "<!-- my comment -->" +
"<optgroup label='my label'>" +
"<option value='1'>option one</option>" +
"</optgroup>";
console.log($(myHtmlString));
console.log($(myHtmlString)[0]);
console.log($(myHtmlString)[1]);
console.log($(myHtmlString).length);
在 Firefox 中,我得到:
在 IE 中,我得到:
因此,显然在 Firefox 中,一个 HTML 注释被添加为该对象的一个元素,但在 IE 中,它不是。为什么会这样,是否存在错误,或者我应该以其他方式创建此对象吗?
注意:我试过 $.parseHTML(myHtmlString)
但它做同样的事情。
更新:这个答案 How does jQuery treat comment elements? 提供了一个潜在的解决方法。
所以这取决于您使用的浏览器,但由于您传递的只是 1 个以上的简单标记,(例如 $('<div>example html creation</div>')
)jQuery 让 浏览器处理创建。
If the HTML is more complex than a single tag without attributes, as it is in the above example, the actual creation of the elements is handled by the browser's .innerHTML mechanism. In most cases, jQuery creates a new element and sets the innerHTML property of the element to the HTML snippet that was passed in.
例如,Firefox 正在查看您的每个 < >
区域,并找到 2 个。而 IE 不关心,并将其全部处理为 1(因此长度为 1)。
长话短说,你做得很好。这只是浏览器内部处理它的方式,您不必担心这些!