hea*_*der 4 javascript each jquery for-loop element
我有以下HTML方案:
<section id="vids">
<ul>
<li>
<a data-reference="12345" href="http://www.youtube.com/watch?v=12345" rel="external" target="_blank">
<span>Video 14</span>
</a>
</li>
<!-- ... -->
</ul>
</section>
Run Code Online (Sandbox Code Playgroud)
以下JavaScript部分:
$(document).ready(function() {
console.log($("#vids a")); // Returns element instance collection
$("#vids a").each(function(i, el) {
console.log(this); // Returns HTMLAnchorElement instead of the element itself
console.log(el); // Same here
console.log(i); // Returns index
});
});
Run Code Online (Sandbox Code Playgroud)
我需要使用方法.removeAttr()和.attr(),但它不起作用,因为.each()返回元素原型而不是它的实例.简单的for循环也存在同样的问题.
Ror*_*san 10
this指的是DOM元素.要在此元素上使用jQuery功能,您需要将其包装在jQuery对象中,即:$(this).
$(document).ready(function() {
console.log($("#vids a")); // Returns element instance collection
$("#vids a").each(function(i, el) {
console.log($(this)); // Will return [Object object]
console.log($(el)); // Same
var $el = $(this);
$el.removeAttr("attribute").attr("foo", "bar");
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4157 次 |
| 最近记录: |