【发布时间】:2014-11-08 17:31:36
【问题描述】:
我在普通聚合物元素中加载 Javascript 时遇到问题:
以下是在没有聚合物的情况下运行良好的测试代码:
<body>
<style>
#content {background-color: #f2f2f2;}
#button {padding: 10px 20px;}
</style>
<div id="content">
<h1 id="title">Title</h1>
<p>This example uses the addEventListener() method to attach a click event to the document.</p>
<button id="button">Testbutton</button>
</div>
<script>
function popup2() {
alert("What's up brow?");
console.log("deine mudda");
};
var button = document.getElementById("button");
button.addEventListener("click", popup2, false);
</script>
</script>
</body>
但我想在 Polymer Elements 中使用 Javascript 并尝试了以下插入:
编号1:脚本标签内的Javascript,模板标签之后:
<polymer-element name="my-element">
<template>
<style>
#content {background-color: #f2f2f2;}
#button {padding: 10px 20px;}
</style>
<div id="content">
<h1 id="title">Title</h1>
<p>This example uses the addEventListener() method to attach a click event to the document.</p>
<button id="button">Testbutton</button>
</div>
</template>
<script>
Polymer('my-element', {
popup: function() {
alert('What the... dude?');
},
var button = document.getElementById("button");
button.addEventListener("click", popup, false);
});
</script>
</polymer-element>
这行不通。我在 Firefox 中收到错误消息:“SyntaxError: missing : after property id. Chrome 反而说:“SyntaxError: Unexpected Identifier”。
都指向“var button = document.getelementById("button"); 行”
根据 Polymer 文档,javascript 应该放在文件末尾: https://www.polymer-project.org/docs/start/tutorial/step-1.html
所以在第二次尝试中,我将 Javascript 直接放在模板标签中,如下所示:
<polymer-element name="my-element">
<template>
<style>
#content {background-color: #f2f2f2;}
#button {padding: 10px 20px;}
</style>
<div id="content">
<h1 id="title">Title</h1>
<p>This example uses the addEventListener() method to attach a click event to the document.</p>
<button id="button">Testbutton</button>
</div>
<script>
function popup() {
alert("jajaja");
};
var button = document.getElementById("button");
button.addEventListener("click", popup, false);
</script>
</template>
<script>
Polymer('my-element', {
});
</script>
</polymer-element>
但是这一次我得到:“Uncaught TypeError: Cannot read property 'addEventListener' of null”,它指向我写的行:“button.addEventListener("click", popup, false);"。
我猜这意味着编译器看不到按钮 id,因为它在 Shadow-Dom 中?
请指教。
【问题讨论】:
-
我不知道如何使用聚合物,但这显然是无效的 JS 语法。它从一个对象开始,然后在中间切换到代码......
-
嘿 Karoly,你建议怎么写?也许这真的只是我对 javascript 的限制,这阻碍了我。我写了三遍代码。您指的是哪一点,语法是否无效,您将如何编写?
-
您收到错误消息,告诉您您使用了无效的语法... ffs,请阅读错误消息。
-
当我将代码实现到聚合物中时,我只会得到错误。在原始 html 文档中,我没有收到任何错误。我在上面写的语法错误,即使在谷歌搜索之后,我也找不到错误,这就是我在这里寻求帮助的原因。
标签: javascript polymer