JQuery循环函数仅适用于最后一个元素

时间:2012-08-03 18:00:51

标签: jquery loops

我正在为新闻页面开发一个简单的JQuery函数。基本上这个想法很简单......我有一个新闻文本div,然后我会为不同的新闻项添加各种按钮。这个想法是当用户点击一个按钮时,div会在数组中加载正确的新闻文本。 似乎只能在最后一个按钮上工作,所以我的循环出了问题。我是新手,所以我有点难过!

HTML CODE

<div id="textbtn0">Btn1</div>
<div id="textbtn1">Btn2</div>
<div id="textbtn2">Btn3</div>
<div id="textbox">This is text</div>

JQUERY CODE

jQuery(document).ready(function() {
    var newsItems=new Array();
    newsItems[0]="News1";
    newsItems[1]="News2";
    newsItems[2]="News3";
    for(a=0;a<newsItems.length;a++){
        var num=a;
        jQuery("#textbtn"+num).mouseover(function() {
             $("#textbtn"+num).css('cursor', 'pointer');
        });

        $("#textbtn"+num).click(function()
        {
            $("#textbox").html(newsItems[num]);
        });
    };
});

5 个答案:

答案 0 :(得分:3)

抱歉,您可以避免在执行更优化的代码时遇到一些问题。 这就是我认为你可以做到的。希望你喜欢! 我创建了一个小提琴(here)以确保它能够像您想要的那样工作。

<div class="textHover" alt="News 1">Btn1</div>
<div class="textHover" alt="News 2">Btn2</div>
<div class="textHover" alt="News 3">Btn3</div>
<div id="textbox" >This is text</div>

jQuery(document).ready(function() {
    jQuery(".textHover").css('cursor', 'pointer');
    jQuery(".textHover").click(function()
    {
        $("#textbox").html($(this).attr('alt'));
    });
});

答案 1 :(得分:0)

这是(a?)jQuery的做法:

jQuery(document).ready(function() {
    var newsItems=new Array();
    newsItems[0]="News1";
    newsItems[1]="News2";
    newsItems[2]="News3";
    for(a=0;a<newsItems.length;a++){
        jQuery("#textbtn"+a).mouseover({num:a},function(e) {
            $("#textbtn"+e.data.num).css('cursor', 'pointer');
        });
        $("#textbtn"+a).click({num:a},function(e){
            $("#textbox").html(newsItems[e.data.num]);
        });
    }
});

编辑:修复错过的点击事件

答案 2 :(得分:0)

我不明白为什么你不会优化一点,我做了,this is the jsFiddle result


为了解释我做了什么,我摆脱了jQuery css声明,并使用了常规的CSS。我将所有ID更改为类,因为它们共享相同类型的信息。此外,鼠标悬停事件应该是完全没必要的,因为cursor: pointer仅适用于所有浏览器中的鼠标悬停。将数组放在一行只是偏好,如果你愿意,可以像你一样单独初始化它。希望你喜欢这个解决方案!

答案 3 :(得分:0)

您只需使用jQuery.each

即可
jQuery(document).ready(function() {
    var newsItems=new Array();
    newsItems[0]="News1";
    newsItems[1]="News2";
    newsItems[2]="News3";
    $.each( newsItems, function(i, l){
        $("#textbtn"+i).mouseover(function() {
            $("#textbtn"+i).css('cursor', 'pointer');
        });
        $("#textbtn"+i).click(function(){
            $("#textbox").html(newsItems[i]);
        });
    });
});

这是一个工作示例=&gt; http://jsfiddle.net/abdullahdiaa/aawcn/

答案 4 :(得分:0)

这些工作示例完全正确。但是我仍然想纠正您的代码。

jQuery(document).ready(function() {
    var newsItems=new Array();
    newsItems[0]="News1";
    newsItems[1]="News2";
    newsItems[2]="News3";
    for(let a=0;a<newsItems.length;a++){
        let num=a;
        jQuery("#textbtn"+num).mouseover(function() {
             $("#textbtn"+num).css('cursor', 'pointer');
        });

        $("#textbtn"+num).click(function()
        {
            $("#textbox").html(newsItems[num]);
        });
    }
});