-3

我有以下代码,它根据触发事件时元素中存在的文本值在单击时更改某个元素中的文本。

http://jsfiddle.net/TNDhL/

$('#left').on('click', function (){
if ($("#textContainer:contains('something')").length) {
    $('#textContainer').text('third text replacement');
    $('.elsewhere').text('more here');
}
else if ($("#textContainer:contains('third text replacement')").length) {
    $('#textContainer').text('now the next item');
    $('.elsewhere').text('something new here');
}
else if ($("#textContainer:contains('now the next item')").length) {
    $('#textContainer').text('new text here');
    $('.elsewhere').text('something else here');
}
else if ($("#textContainer:contains('new text here')").length) {
    $('#textContainer').text('something');
    $('.elsewhere').text('text here');
}
});

$('#right').on('click', function (){
if ($("#textContainer:contains('something')").length) {
    $('#textContainer').text('new text here');
    $('.elsewhere').text('something else here');
}
else if ($("#textContainer:contains('new text here')").length) {
    $('#textContainer').text('now the next item');
    $('.elsewhere').text('something new here');
}
else if ($("#textContainer:contains('now the next item')").length) {
    $('#textContainer').text('third text replacement');
    $('.elsewhere').text('more here');
}
else if ($("#textContainer:contains('third text replacement')").length) {
    $('#textContainer').text('something');
    $('.elsewhere').text('text here');
}
});

请参阅上面的小提琴以获取工作版本。

我想找到一种方法让它更易于管理,以便更容易扩展它。有没有更好的方法来处理这种情况?将其压缩成一个函数并使用变量来存储 #textContainer 的值会更理想。有什么建议么?

4

1 回答 1

1

似乎是一个完美的闭包案例,它可以用一个简单的计数器跟踪你的进度。看起来像这样:

var myTextRotator = (function () {
    var myPhraseArray = ["first phrase", "second phrase"],
        counter = 0;
    return {
       clickLeft: function () {
           counter -= 1;
           return myPhraseArray[counter]; //return array item or do your processing here
       },
       clickRight: function () {
           counter += 1;
           return myPhraseArray[counter]; //return array item or do your processing here
       }
    };
}());

clickLeftandclickRight方法绑定到 jQuery .on()。可能必须在其中添加一个条件,以便计数器不会低于 0 或高于数组长度。

你会这样使用:

$(".left").on("click", function () {
    myTextRotator.clickLeft();
});

$(".right").on("click", function () {
    myTextRotator.clickRight();
});
于 2013-09-16T16:28:07.137 回答