0

我有一个小脚本,它使li元素可点击并将位置设置为li. 这运行没有错误,我的两个console.log()电话报告了我所期望的,但是,当您单击li(无论哪个li)时,您将被带到href最后一个链接的li. 这对我来说没有多大意义,因为我认为我已经正确处理了范围。

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

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>
4

1 回答 1

3

前缀$href,var使变量保持本地
目前,您正在覆盖一个$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');
}); 
于 2012-05-06T19:51:07.943 回答