[英]How can I achieve click event in JavaScript?
I select a span element on the page.我在页面上选择了一个 span 元素。 For the first click, I want it to link to another page.
对于第一次点击,我希望它链接到另一个页面。 On the second click, I want it to return to the original page.
在第二次单击时,我希望它返回到原始页面。
For example, I have a link with example.com
, which is the original.例如,我有一个与
example.com
的链接,这是原始链接。 When this element "abcd" is clicked I want it to link to example.com/ar
, and when it's clicked again I want it to go back to example.com
.当这个元素“abcd”被点击时,我希望它链接到
example.com/ar
,当它再次点击时我希望它返回到example.com
。
document.querySelector('span.arb').addEventListener('click', function() {
a.href="example.com";
})
How do I complete this using the above?如何使用上述方法完成此操作?
Try this:尝试这个:
let count = 0; document.querySelector('span.arb').addEventListener('click', function () { count++; document.querySelector('a').href = "http://example.com"; if (count == 1) { document.querySelector('a').href = "http://example.com/ar"; } else { document.querySelector('a').href = "http://example.com"; } });
<a href="http://example.com">Link</a> <span class="arb">Click Me</span>
you can get link and change her after click你可以得到链接并在点击后改变她
document.querySelector('span.arb').addEventListener('click', toogle)
function toogle(){
if( document.querySelector('span.arb').href === "domain.com"){
document.querySelector('span.arb').href = "domain.com/link"
} else if (document.querySelector('span.arb').href === "domain.com/link"){
document.querySelector('span.arb').href = "domain.com"
}
Hold the link in a data attribute and use that to toggle.将链接保存在数据属性中并使用它进行切换。
document.querySelector("[data-toggleHref]").addEventListener("click", function(){ //Get the link element var a = document.querySelector("a"); var current = a; //Log to demontrate only console.log(this.dataset.togglehref); //Update the link a.href = this.dataset.togglehref; //Set the data attribute for toggle this.dataset.togglehref = current; });
<a href="/pagea.html" id="target">Link</a> <span data-toggleHref="/pageb.html">Click Me</span>
try this code:试试这个代码:
document.querySelector('span.arb').addEventListener('click', function() {
if(a.href == "example.com") {
a.href="example.com/ar";
} else {
a.href="example.com";
}
})
or a shorter answer using ternary operator:或使用三元运算符的简短答案:
document.querySelector('span.arb').addEventListener('click', function() {
a.href = a.href == "example.com" ? "example.com/ar" : "example.com";
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.