gpt4 book ai didi

javascript - 对象 HTMLAnchorElement] 没有方法 'attr'

转载 作者:行者123 更新时间:2023-11-28 15:45:50 24 4
gpt4 key购买 nike

我想在每个菜单项前面添加浏览器中存在的 URL(由于某些 url 重定向内容而必须这样做)。但它在下面提到的行中给出了错误。我究竟做错了什么?正确的做法是什么?

          $(window).load(function () {
var Home = window.location.pathname;
alert(Home);
path = $("#menu ul li a");

$.each(path, function (key, value) {
console.log(value);
alert(value);
            //These line give error: 
//Object [object HTMLAnchorElement] has no method 'attr'
                var link =  value.attr("href");
value.attr("href", Home + link );
});


});

HTML

 <div class="menu" id="menu">
<ul>
<li><a href="Index.html">Home</a></li><div class="menuline"></div>
<li><a href="Products.html">Products</a></li><div class="menuline"></div>
<li><a href="Albums">Photos</a></li><div class="menuline"></div>
<li><a href="#">Contact</a></li><div class="menuline"></div>
</ul>

最佳答案

您需要 jQuery 对象而不是 Dom 来调用 attr(),因为 each() 为您提供 DOM对象不是 jQuery 对象

$(value).attr("href", Home + link );

也可以使用DOM对象直接给href赋值

value.href = Home + link;

The .each() is used directly on a jQuery collection. It iterates over each matched element in the collection and performs a callback on that object. The index of the current element within the collection is passed as an argument to the callback. The value (the DOM element in this case) is also passed, but the callback is fired within the context of the current matched element so the this keyword points to the current element as expected in other jQuery callbacks, jQuery docs.

关于javascript - 对象 HTMLAnchorElement] 没有方法 'attr',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22342780/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com