2

这是我在网站上的第二篇文章。在我尝试过的所有其他网站中,这个网站提供了最准确和最有用的信息!

我的按钮有点麻烦,我有一个任务是创建一个收件箱并在每个消息实例中添加一个“回复”和“删除”按钮。

如果有比将 HTML 代码强制写入脚本更好的方法,我确实在徘徊,因为每条消息都是动态生成的。任何帮助和/或建议将不胜感激!(对象是从 JSON 文件调用的)。

$(document).ready(function(){
    $.getJSON('public/js/data.json', function(json){
        $.each(json.data, function(i, data){
            var output = '';
         if(data.from.id != '234' && data.from.name != 'Alan Ford'){

            $("#inbox").append(
            output +=
            '<div class="post">'+
            '<div class="h1">'+data.from.name+' - '+data.subject+'</div>'+ //this gives the name of the person who sent the message and the subject
            '<div class="content">'+data.message_formatted+'</div>'+ //The content of the message
                         //buttons should be squeezed left of the date
                           //this gives the date of the message sent
             '<div class="time">'+data.date_sent_formatted.formatted+'</div>'+ 
            '</div>'
    );
         }});
    });

});
var date_sent=convertToDateTime();

function delete_message(id){
    console.log('Delete message with id: '+id);
}

function reply_message(id, sender){
    console.log('Message id: '+id);
    console.log('Reply to: '+sender);
}
4

1 回答 1

2
$(document).ready(function() {            //when de html document is loaded
    $(".deleteButton").each(function() {  //for each button with class *deleteButton*
        var button = this;                //we take the html element
        $(button).click(function() {      //and we bind an eventlistener onclick
            alert($(button).attr("id"));  //when the user clicks we tell him the id 
            // code to execute when the user clicks on a delete button
        });
    });

    $(".replyButton").each(function() {
        var button = this;
        $(button).click(function() {
            alert($(button).attr("id"));
            // code to execute when the user clicks on a reply button
        });
    });
});

有了这个,你可以为 html 中的每个删除/回复按钮添加一个类和 id。假设您有一个像这样的简单列表。

<div> 
    <button class="deleteButton" id="1">Message 1</div>
    <button class="replyButton" id="1">Message 1</div>

    <button class="deleteButton" id="2">Message 2</div>
    <button class="replyButton"  id="2">Message 2</div>

    <button class="deleteButton" id="3">Message 3</div>
    <button class="replyButton"  id="3">Message 3</div>
</div>

现在,如果您单击其中一个按钮,您将收到一条警报,告诉您该按钮的 ID。

于 2012-09-04T20:51:09.523 回答