我对使用 jQuery/JavaScript/Ajax 时的最佳实践有疑问。假设我有一些任务,并且每个任务都有一个日历。用户可以单击任务日历中的一天,并通过 AJAX 在特定日期预订任务。我必须将任务的日期和 ID 存储在某处,我为此使用了非常奇怪的 ID,例如:
<span class="day_field" id="date_13-02-2013_task_4">13.02.2013</span>
然后我就像这样附加一个监听器:
$('.day_field').on('click',function(){
var date = $(this).id.split('_')[1];
var task_id = $(this).id.split('_')[3];
//place for some validation
$.post('book_task.php',{task_id: task_id, date: date},function(data){
//something cool with the result
});
});
我的问题是:这是正确的做法吗?我不太确定,因为 ID 可能非常长 + 它包含数据库中的 ID,可能根本不会保存。
谢谢!
最佳答案
使用 HTML5 数据属性:
<span class="day_field" data-date="13-02-2013" data-task="4">13.02.2013</span>
$('.day_field').on('click',function(){
var date = $(this).data("date");
var task_id = $(this).data("task");
//place for some validation
$.post('book_task.php',{task_id: task_id, date: date},function(data){
//something cool with the result
});
});
关于javascript - jQuery 和 AJAX 调用的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15100647/