简体   繁体   English

javascript中的动态列表如何从具体调用function<li></li>

[英]dynamic list in javascript how to call function from specific <li>

I get the message list from the API and create a dynamic array using javascript.我从 API 获取消息列表,并使用 javascript 创建一个动态数组。 I would like a new page with message details to be started when a specific row is pressed.我希望在按下特定行时启动一个包含消息详细信息的新页面。 How do I implement a call to showMessage () on a specific table row?如何在特定表行上实现对 showMessage () 的调用?

var list = document.getElementById("listOfMessage");
init();
function init() {
    for (var i = 0; i < messageList.length; i++) {
        var message = messageList[i];
        var li = document.createElement("li");
        var a = document.createElement("a");
        var text = document.createTextNode("Nadawca: " + message.fullName);
        a.appendChild(text);
        a.setAttribute('onclick', showMessage(message));
        list.appendChild(li);
        //list.innerHTML += "<li><a href="showMessage(message)"><h2>Nadawca: " + message.fullName + " 
        //</h2></a></li>";
    }
    //list = document.getElementById("listOfTask");
}
function showMessage(message) {
    window.sessionStorage.setItem("message", JSON.stringify(message));
    window.location.href = 'message.html';
}

In the code above, the showMessage () function is immediately called when the array is initialized.在上面的代码中,showMessage() function 在数组初始化时立即被调用。 How to make it run only after clicking on a row?如何使其仅在单击一行后运行?

I could add an id attribute to the (a) or (li) element in the init () function, but how to find it later and use it in this code:我可以在 init () function 中的 (a) 或 (li) 元素中添加一个 id 属性,但是以后如何找到它并在此代码中使用它:

var a = document.getElementById('1');
a.addEventListener('click', function() {
    window.sessionStorage.setItem("message", JSON.stringify(messageList[0]));
    window.location.href = 'message.html';
});

I found a way to solve this problem.我找到了解决这个问题的方法。 Using this code fragment, we can call a function for a specific element in a dynamically created list.使用此代码片段,我们可以为动态创建的列表中的特定元素调用 function。

function init() {
    for (var i = 0; i < messageList.length; i++) {
        var message = messageList[i];
        list.innerHTML += "<li id="+i+"><a onClick="+
        "><h2>Nadawca: " + message.fullName + "</h2></a></li>";
    }

    //$(document).on("click", "ui-content", function(){ alert("hi"); });
    $(document).ready(function() {

        $(document).on('click', 'ul>li', function() {  
            var idName = $(this).attr('id');
            showMessage(messageList[idName]);
        });
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM