当从服务器生成 HTML 时,例如,通过 PHP 中的 echo
,分配事件是否更好:
<div>
<input type="button" onclick="Click(123)"/>
</div>
function Click(x)
{
var id = x;
//Do Ajax Call
}
或者在 JQuery/JavaScript 中声明事件...
<div id="123">
<input type="button" class="myButton"/>
</div>
$(".myButton").click(function(){
//Fetch the ID as well
var parentID = $(this).parent('div').attr('id');
//Then do an Ajax Call
});
哪个是最佳实践?
最佳答案
HTML 是否动态生成没有区别。您通常应该更喜欢使用 unobtrusive Javascript无论哪种方式。
关于javascript - 动态生成的 HTML、生成的事件与静态脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15453020/