JavaScript 语法错误
var dayNumberCell = doc.createElement('td');
dayNumberCell.className = 'days_link';
dayNumberCell.setAttribute('onclick', function(scope) {
var bindScope = function() {
scope.changeDate(this, this.id);
scope.returnDate(scope.month, scope.year);
};
return bindScope;
}(this));
上面的代码生成 tds onclick 事件监听器。生成的代码看起来像
<td class="days_link" onclick="function () {
scope.changeDate(this, this.id);
scope.returnDate(scope.month, scope.year);
}">15</td>
通过单击 TD 我收到语法错误消息。 我应该如何编写指定代码执行并且没有语法错误的函数。
提前致谢。
var dayNumberCell = doc.createElement('td');
dayNumberCell.className = 'days_link';
dayNumberCell.setAttribute('onclick', function(scope) {
var bindScope = function() {
scope.changeDate(this, this.id);
scope.returnDate(scope.month, scope.year);
};
return bindScope;
}(this));
The above code generates tds onclick event listener. and the generated code looks like
<td class="days_link" onclick="function () {
scope.changeDate(this, this.id);
scope.returnDate(scope.month, scope.year);
}">15</td>
By clicking on TD I get syntax error message.
How should I write my function that the specified code executes and also have no syntax error.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您将函数定义放在字符串文字中。它期待的是代码,而它所拥有的只是文本。
You put your function definition inside a string literal. It's expecting code and all it has is text.
您应该按如下方式重写您的 onclick 处理程序:
我不明白为什么您会尝试从外部 js 文件设置内联点击处理程序。您采取了正确的步骤从 html 中删除内联点击处理程序,但是当您从外部脚本设置点击处理程序时,您不应该设置 onclick 属性。
除了我强调的方法之外,您还可以使用 w3c 和 microsoft 事件处理程序,以便可以将多个 onclick 事件附加到同一元素。然而,这是一种更复杂的方法,因为不同的浏览器对其处理方式有所不同。只要您不打算将其他 onclick 处理程序附加到同一单元格,这就足够了。
You should rewrite your onclick handler as follows:
I don't understand why you would try to set the inline click handler from an external js file. You took the right step to remove inline click handlers from your html, but when you set the click handler from an external script, you should not be setting the onclick attribute.
In addition to the way I highlighted, you could use the w3c and microsoft event handlers so that you can attach multiple onclick events to the same element. However, this is a more complicated approach since different browsers handle it differently. This will suffice as long as you don't plan to have other onclick handlers attached to the same cell.
你在函数之外尝试过吗?
如果这不起作用,请在您的 javascript 文件上尝试一下,是的,使用一个函数。
Have you tried outside the function?
if that don't work, try it on your javascript file, and there, yes, with a function.
也许您不想使用任何 javascript 库,但我强烈建议您使用 YUI Event 实用程序来实现此目的。
达斯汀·迪亚兹(Dustin Diaz)有一篇很棒的文章,解释了它如何为您简化这一过程。
http://www.dustindiaz.com/yahoo-event-utility/
Perhaps you would prefer not to use any javascript libraries, but I would highly recommend using the YUI Event utility for this.
Dustin Diaz has a great article that explains how it would simplify this for you.
http://www.dustindiaz.com/yahoo-event-utility/