我可以修改此脚本以使用多个DIV标记吗?

这是我目前的代码:
var text = ['foo', 'bar', 'baz'];
    i = 0,
    $div = $('#myDiv');

setInterval(function ()
{
    $div.fadeOut(function ()
    {
        $div.text(text[i++ % text.length]).fadeIn();
    });
}, 1000);
有人可以告诉我如何在同一页面上使用多个DIV标签吗?现在它只适用于一个。 埃里克     
已邀请:
目前还不完全清楚你要做什么,但也许是这样的:
//get all the div elements with the given classname
divs = document.getElementsByClassName("myDivClassName");

//for each div, apply the update on a timer
setInterval(function () {
    for (var index = 0; index < divs.length; index++) {
        var div = divs[index];
        div.fadeOut(function () {
            div.text(text[i % text.length]).fadeIn();
        });
    }
    i++;
}, 1000);
    
使用jQuery.each和/或选择器(我假设你使用jQuery?) jQuery.each(集合,回调(indexInArray,valueOfElement)) http://api.jquery.com/jQuery.each/   通用迭代器函数,可用于无缝迭代对象和数组。具有length属性的数组和类似数组的对象(例如函数的参数对象)由数字索引迭代,从0到length-1。其他对象通过其命名属性进行迭代。 选择 http://api.jquery.com/category/selectors/   允许您选择特定jQuery选择器的元素。您可以在jQuery选择器文档页面上找到可能的选择器列表。     
<script type="text/javascript">

   var text = ['foo', 'bar', 'baz'];
   i = 0,
   $divs = $('#DIV1, #DIV2');// or $('div.class1') for all divs
                             // with class='class1'

   setInterval(function ()
   {
       $divs.fadeOut(function (){
                        $(this).text(text[i++ % text.length]).fadeIn();
                    });
   }, 1000);

</script>
    

要回复问题请先登录注册