gpt4 book ai didi

javascript - jQuery .each 被广泛应用

转载 作者:行者123 更新时间:2023-11-28 21:03:23 26 4
gpt4 key购买 nike

我有一个小脚本,它使 li 元素可点击,并将位置设置为 li 内部链接的位置。它运行时没有错误,并且我的两个 console.log() 调用正在报告我所期望的内容,但是,当您单击 li (以 li)您将获取最后一个 li 中链接的 href。这对我来说没有多大意义,因为我认为我已经正确处理了范围。

请纠正我的理解并让我知道我哪里错了。

JavaScript:

$(".homeCTA li").each(function(){
$href = $(this).find("a").attr("href");
console.log($(this)); // displays the expected selector
console.log($href); // displays the correct href
$(this).click(function(){ window.location = $href }); // this is overriding all of the previous passes
});

HTML:

<ul class="homeCTA">
<li class="left">
<img src="first-source.jpg">
<h2><a href="SearchResults.asp?Cat=1833">Yada Yada Yada</a></h2>
</li>
<li class="right">
<img src="second-source.jpg">
<h2><a href="SearchResults.asp?Cat=1832">Try the bisque</a></h2>
</li>
</ul>

最佳答案

$href前面加上var,这样变量remains local .
目前,您正在覆盖 $href 变量,该变量在循环中不断被覆盖。

$(".homeCTA li").each(function(){
var $href = $(this).find("a").attr("href");
console.log($(this)); // displays the expected selector
console.log($href); // displays the correct href
$(this).click(function(){ window.location = $href; });
});

您还可以使用以下代码,而不是循环遍历列表项:

$(".homeCTA").on('click', 'li', function(){
window.location = $(this).find('a').attr('href');
});

关于javascript - jQuery .each 被广泛应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10473715/

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