这是我在网站上发布的第二篇文章。在我尝试过的所有其他网站中,这个网站提供了最准确、最有用的信息!
我在使用按钮方面遇到了一些麻烦,我的任务是创建一个收件箱并在消息的每个实例中添加“回复”和“删除”按钮。
我确实在想是否有比将 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);
}
最佳答案
$(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。
关于javascript - 在Jquery中制作删除和回复按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12271042/