具体来说,我说的是避免这种类型的代码:
<input type='text' id='title_33' class='title'
onfocus='updateCharsLeft(33);'
onkeypress='updateCharsLeft(33);' />
在这里,我想将 onfocus
和 onkeypress
事件句柄分开放置,即放在 .js 文件中。像这样:
$(document).ready(function()
{
$(".title").focus(updateCharsLeft);
$(".title").keypress(updateCharsLeft);
);
但是这里的问题是文本框的 ID 需要传递给函数 updateCharsLeft()
。在该函数中必须从文本框的 ID 中提取 ID 会很糟糕,所以实际上将事件处理程序放入 HTML 代码中会更清晰。
想法?
最佳答案
你不能这样做吗:
$(document).ready(function()
{
$(".title").focus(function() {
updateCharsLeft(this.id);
});
$(".title").keypress(function() {
updateCharsLeft(this.id);
});
);
或更简洁:
$(document).ready(function()
{
$(".title .another .someother .andAnother").focus(function() {
updateCharsLeft(this.id);
}).keypress(function() {
updateCharsLeft(this.id);
});
);
关于javascript - javascript 和 HTML 是不可能分开的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1097459/