循环浏览备用文本

时间:2013-02-05 23:19:33

标签: arrays text for-loop onclick cycle

完成新手,试图创建一个可个性化的圣经,用户可以通过直接点击所述单词/短语来循环翻阅单个单词/短语的替代翻译。我知道我可能需要在函数中使用某种“for循环”,但是我希望它们的首选项在缓存和用户配置文件中存储(作为字符串?),因此在页面加载时文本不应重置为默认值。理想情况下,我会在HTML中嵌入替代文本选项(“数组”?),如下所示,同时保持HTML尽可能整洁。 JS最终将填充成千上万的ID,可能是每节经文中的几个ID,因此脚本越通用越好。提前谢谢!

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.js"></script>
<script>
$(document).ready(function() {
    $('.alternate').click(function() {
        $('#1Cor13-4a').text('[What goes here if I want to cycle through the options listed in HTML?]');
        $('#1Cor13-4b').text('[Ditto]');
    });
});
</script>

My <span class="alternate" id="1Cor13-4a" onclick="ChangeText({"care","love"})">love</span><span class="alternate" id="1Cor13-4b" onclick="ChangeText({"is patient with","suffers long for"})">is patient with</span> you.

1 个答案:

答案 0 :(得分:1)

使用数据属性......

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.js"></script>
<script>
$(document).ready(function() {
 $('.alternate').click(function() {
       var index=   $(this).attr("data-text-index");
     var text = $.parseJSON($(this).attr("data-text"));
     if(index== null)
         index = -1;
     index = Number(index)+1>=text.length? 0:Number(index)+1;
     $(this).html(text[index]);
     $(this).attr("data-text-index",index);
  });
});
</script>
My <span class="alternate" id="1Cor13-4a" data-text='["care","love"]'>love</span><span class="alternate" id="1Cor13-4b" data-text='[" is patient with"," suffers long for"]'> is patient with</span> you.