I have a script called main.js that is attached to index.html. I have an onclick()
function set up within index.html that needs to change the value of a variable. This question would be easy if the script was written with script tags, however, despite trying to figure it out, I'm not sure how to do it when the script is referenced via a script tag. The code isn't really relevant to the question, but here's the line anyway.
<li><a href="main.html" onclick='card=thing;'>thing</a></li>
card is a variable in main.js which needs to be changed. In main.js, before the onclick()
event, card is set to NULL. Thanks so much.
答案 0 :(得分:0)
在home.js中编写一个函数,并且可以在该函数内部编写并访问href变量。
html应该是这样的
<li><a id="variable" href="main.html" onclick='card=thing;'>thing</a></li>
在您的函数中添加此行
document.getElementById("variable").href="your reference";
答案 1 :(得分:0)
您可以在脚本标签或main.js中编写函数,然后在onclick上调用它
<li><a href="javascript:void(0)" onclick='changeCard("thing")'>thing</a></li>
<script type="text/javascript">
function changeCard(val) {
card = val;
}
</script>
答案 2 :(得分:0)
我认为您的代码在语法上是可以的,因为如果main.js文件链接到同一行所在的html,则card
是一个全局变量,您可以毫无问题地覆盖它。
尽管这种情况下的问题可能是其他问题,因为当用户单击指向其href属性中指向main.html文件的锚标记时,您正在更改该变量。
所以实际发生的是将执行两个事件处理程序,第一个将是您的代码来更改该变量的值,第二个将实际上将您的窗口重定向到另一个html文件,从而更改当前事件的实际上下文窗口并使其全局变量不再有用,这没有任何意义。
如果您想在导航到其他地方之前在js中做某事,则需要将事件处理程序附加到anchor元素,并调用event.preventDefault()
方法以防止点击click标签时默认的行为,换句话说,防止导航。看起来像这样:
// Js code:
var anchor = document.querySelector('a')
anchor.addEventListener('click', function(event) {
event.preventDefault()
// Do the stuff you want to do on click here, before navigating, etc
card = thing
// ... explicitly navigate
})