简体   繁体   English

为什么我不能在HTML中使用被称为'evaluate'的JS函数?

[英]Why Can't I Use JS Function Called 'evaluate' in HTML?

I'm kind of curious why this doesn't work 我有点好奇为什么这不起作用

JavaScript: JavaScript的:

function evaluate(){
    console.log(42);
}

HTML: HTML:

<a onclick="evaluate()">Click Me!</a>

Is evaluate a reserved keyword somewhere on the html side? 在html端评估一个保留关键字?

"evaluate" is not a reserved keyword, but when it's used in inline event handler, it happens to collide with document's evaluate function( document object is within handler's scope chain before the window object). “evaluate”不是保留关键字,但是当它在内事件处理程序中使用时,它碰巧与文档的evaluate函数碰撞( document对象在window对象之前位于处理程序的作用域链中)。 If you don't want to change your function name, just add window context before it, ie 如果您不想更改您的函数名称,只需在它之前添加window上下文,即

<a onclick="window.evaluate()">Click Me!</a>

document.evaluate需要解析个XML,看到在MDN参考这里

Evaluate is not a reserved word in JavaScript, document.evaluate is used to evaluate XPath expressions. Evaluate不是JavaScript中的保留字document.evaluate用于评估XPath表达式。

You could still name your function evaluate if you used a less obtrusive method of attaching your event handler: 如果你使用一种不那么突兀的方法来附加你的事件处理程序,你仍然可以命名你的函数evaluate

var evaluate = function (){
    console.log(42);
}

document.addEventListener('click', evaluate, false);

Example

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我不能在Nightmare.evaluate()中使用我的课程? - Why can't i use my class in Nightmare.evaluate()? 为什么我不能在单独的html和js文件中使用全局变量? - Why can't I use globals in separate html and js files? 为什么我不能在其他JS文件中使用该功能? - Why can't I use the function in other JS file? 评估函数中的 JS 无法执行 - the JS in evaluate function can't been executed 我可以在 function arguments 中对 Strings 在 JS 中使用逻辑或运算符吗? Function 不评估第二个字符串(我认为) - Can I use the logical OR operator with Strings in function arguments in JS? Function does not evaluate the second string (I think) 基本的Javascript / jQuery数学游戏:为什么我第二次运行此函数不能评估? - Basic Javascript / jQuery math game: Why can't I evaluate the second time I run this function? 创建js对象时,为什么不能在另一个已定义函数中使用已定义函数? - Why can't I use a defined function inside another defined function,when creating an js object? 我无法在Vue js的HTML中使用JS脚本 - I can't use a JS script in my HTML with Vue js 为什么我不能使用javascript函数在html画布上绘制多个图像? - Why can't I use a javascript function to paint more than one image on an html canvas? 为什么我只能在spookyjs(casperjs)中评估匿名函数 - Why can I only evaluate an anonymous function in spookyjs (casperjs)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM