保存特定onclick元素的ID

时间:2014-01-15 08:20:09

标签: javascript

我正在尝试创建一个JavaScript,您可以在其中编写消息,并在网站上显示时间和消息。执行此操作的功能是“renderMessage”。但是,它包含一个图像,您可以单击以删除该消息,然后我想再次编写所有剩余的图像。问题是我不知道如何保存某种ID,所以我知道点击了哪个图像,所以我删除了消息数组中的正确位置。

renderMessage的代码是:

function renderMessage(theMessage, theMessages){
    var text = document.createTextNode(theMessage.getText());
    var time = document.createTextNode(theMessage.getDate());
    var div = document.getElementById("writeMessages");

    div.appendChild(text);
    div.appendChild(time);

    var image = document.createElement('img');
    image.src = 'img/deletePic.png';

    div.appendChild(image);
    div.appendChild(document.createElement('br'));

    image.onclick = function(e){

        theMessages.splice(); // This is where I don't know how to remove the correct one
        removeAll(theMessages); // This removes all html code in the div and writes 
                                // the array again (hopefully this time with the correct
                                // element removed from it)
    };
}

2 个答案:

答案 0 :(得分:0)

您可以将消息的id保存在元素的属性中。例如<div class="your_message_container data-id="14">...</div>

例如,使用jquery,您可以使用$(your_selector).attr("data-id");读取该属性,并将其写为$(your_selector).attr("data-id", "new_value");

作为替代方案,请查看http://api.jquery.com/jquery.data/

编辑:

我让你成为纯js的小提琴:http://jsfiddle.net/A64zh/2/注意,message元素的id必须等于你删除图像的data-message-id属性。

使用元素属性存储id的优点是你的javascript不依赖于html结构,就像你使用this.parentNode.parentNode.removeChild....之类的东西一样,如果要添加更多内容则需要更改html图层介于两者之间

答案 1 :(得分:0)

首先,赞成使用普通的js。

我会说你将消息,时间和图像包含在另一个元素中。我是ul li块。并且,当您在DOM中呈现消息时,您将消息ID设置为id的{​​{1}}属性,因此它将是这样的

li

你的js代码可以是,

<ul>
    <li>Message 1 - 10:21 PM <img src="remove jpg"/></li>
    <li>Message 2 - 10:22 PM <img src="remove jpg"/></li>
</ul>

为什么要重新渲染所有邮件?你可以简单地

image.onclick = function () {
    var message_id = this.parentNode.id;

    // here you got the message id.
    // splice your message array and render
}