我想知道,将 javascript 函数放在 html 标签中是否更好,例如
<form method="post" action="/web/comment"
onsubmit="jQuery.ajax({
type:'POST',
dataType:'html',
data:jQuery(this).serialize(),
success:function(data, textStatus) {
jQuery('#comment').html(data);
},
url:'/web/comment'
});
return false;">
或者在外部文件中,例如 script.js?
最佳答案
考虑可读性(对于人类)——在您的示例中,代码在单独的文件中(如您所建议的)或在您的 html 文件中的 script
block 中肯定会更具可读性。
例如
<script type="text/javascript">
function submitComments(commentsForm) {
jQuery.ajax({
type:'POST',
dataType:'html',
data:jQuery(commentsForm).serialize(),
success:function(data, textStatus) { jQuery('#comment').html(data); },
url:'/web/comment'
});
}
</script>
和
<form method="post" action="/web/comment" onsubmit="submitComments(this); return false;">
关于 jQuery 的一些提示
- 与其直接设置
onsubmit
属性,不如查看 jQuery's event binding syntax .这使您可以将事件处理代码及其管道很好地封装在一个地方,这通常会使您的代码更易于人们理解。 - 在您的代码中简单地使用简写
$
而不是jQuery
更为常见(除非$
已经被定义为具有某种意义否则)。
关于javascript - 在文件或 html 标签中使用 javascript 函数更好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7482489/