【问题标题】:check data against array and display next element with jquery mobile function根据数组检查数据并使用 jquery 移动功能显示下一个元素
【发布时间】:2014-02-03 17:37:36
【问题描述】:

我需要将数组中的项目与 html 页面中的项目进行比较的指导。首先,我有一个填充了需要显示的各种元素的数组。我的目标是在当前显示的 html 页面(或我正在显示的其他 div)的标题中获取当前内容,并将其与数组中的每个元素进行比较。一旦找到匹配项,我想在 html 页面中显示下一个索引的内容。单击“下一步”按钮时应执行此功能。如果有人能提供帮助,我将不胜感激!

这是数组填充的内容:

var item = {title: displayTitle, link: linkUrl, infoDescription: infoDisplay, Date: new Date(eventDate), Region: region,}

这是页面以及我要调用该函数的按钮:

<div data-role="page" id="eventPage"> <!-- Start Event Page -->
    <div data-role="header" data-position="fixed" data-theme="b">
            <a href="#home" data-role="button" data-icon="home" data-iconpos="notext">Home</a>
            <h1>Mobile</h1>
            <a href="#" onclick="next_event()" target="_blank" data-role="button" class="next"  data-icon="forward" data-iconpos="notext">Next</a>

    </div>
    <div data-role="content">
        <div id="page-title"></div>
        <div id="page-date"></div>
        <div id="page-content"></div>
    </div> 

    <div data-role="footer" data-theme="d" data-position="fixed"></div>
</div><!-- End eventPage -->

这是我为测试这个想法而创建的函数。现在,该函数只显示数组中的每个标题。我不想附加数据,我想替换它。也许替换?

function next_event() {
    $.each(data, function(i,item){ // notice the item


    $('#page-title').append(item.title);


});
}

【问题讨论】:

    标签: javascript jquery html arrays function


    【解决方案1】:

    您只需要更改 DOM 节点的文本。首先,您必须缓存节点以防止每次单击按钮时都选择它们。

    var nodes = {
        title: $('#page-title'),
        date: $('#page-date'),
        content: $('#page-content'),
    };
    

    你也可以缓存当前选中项的索引:

    var currentIndex = 0;
    

    每次按下按钮时 - 计数器应该增加并且节点的文本会改变:

    $('.next').click(function () {
        currentIndex++;
        if (currentIndex >= data.length) {
            currentIndex = 0;
        }
        nodes.title.text(data[currentIndex].title);
        nodes.date.text(data[currentIndex].date);
        nodes.content.text(data[currentIndex].infoDescription);
    });
    

    jsfiddle 中查看演示。

    【讨论】:

    • 感谢您的解决方案,jsfiddle 正是我想要的!但是,我将它放在我的代码中并且没有运气进行测试。我在任何函数之外声明了 var data = [] 所以我不确定问题是什么。有什么建议吗?
    • 这就是所有出现的:event.returnValue 已被弃用。请改用标准 event.preventDefault()。
    • 此外,在我执行按钮单击之前出现了该错误。当我单击下一个按钮时,控制台中什么也没有出现。
    • 你包含了 jQuery 吗?你能创建一个 jsfiddle 并尽可能多地发布你的代码吗?
    • 1.包括 jQuery(jsFiddle 页面的左上角) 2. html 呢?也很高兴看到它
    猜你喜欢
    • 2018-02-23
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-24
    相关资源
    最近更新 更多