Cli*_*ote 5 javascript jquery code-organization
具体来说,我在谈论避免这种类型的代码:
<input type='text' id='title_33' class='title'
onfocus='updateCharsLeft(33);'
onkeypress='updateCharsLeft(33);' />
Run Code Online (Sandbox Code Playgroud)
在这里,我想分别放置onfocus和onkeypress事件句柄,即在.js文件中.像这样:
$(document).ready(function()
{
$(".title").focus(updateCharsLeft);
$(".title").keypress(updateCharsLeft);
);
Run Code Online (Sandbox Code Playgroud)
但是问题是文本框的ID需要传递给函数updateCharsLeft().如果必须从该函数中的文本框的ID中提取出id,那么在HTML代码中放入事件处理程序实际上会更加清晰.
思考?
你不能这样做:
$(document).ready(function()
{
$(".title").focus(function() {
updateCharsLeft(this.id);
});
$(".title").keypress(function() {
updateCharsLeft(this.id);
});
);
Run Code Online (Sandbox Code Playgroud)
或者更整洁:
$(document).ready(function()
{
$(".title .another .someother .andAnother").focus(function() {
updateCharsLeft(this.id);
}).keypress(function() {
updateCharsLeft(this.id);
});
);
Run Code Online (Sandbox Code Playgroud)
我之前曾做过类似的事情,并且对解析 ID 属性的值也不满意。我可以建议的最好的事情是您使用另一个属性来获取您需要的值,例如属性rel:
<input type='text' id='title_33' class='title' rel='33' />
Run Code Online (Sandbox Code Playgroud)
或者根据您对验证的虔诚程度,只需使用自定义属性:
<input type='text' id='title_33' class='title' myval='33' />
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1404 次 |
| 最近记录: |