2017-02-23 52 views
-3

需要帮助随时间替换文本在JavaScript

  1. 当任何链接被点击的文本(不点击)应由及时更换。

    <div><a href="http://facebook.com">Facebook(NOT CLICKED)</a></div> 
    <div> 
        <ul> 
         <li><a href="http://youtube.com">Youtube(NOT CLICKED)</a></li> 
        </ul> 
    
+0

发表一些你的HTML不是链接到Facebook和YouTube! –

+0

@ibrahimmahrir我已更新它 –

+0

如果点击链接,您将被重定向,任何更改都将丢失!你想防止点击的默认行为? –

回答

1

var links = document.querySelectorAll("a"); 
 
links.forEach(function(l) { 
 
    l.addEventListener("click", clickHandler); 
 
}); 
 

 
function clickHandler(ev) { 
 
    ev.preventDefault(); // don't redirect (don't go the the link in the href) 
 
    
 
    this.textContent = this.textContent.replace("(NOT CLICKED)", "(" + Date() + ")"); // replace the text "(NOT CLICKED)" with "(date)" 
 
}
<div><a href="http://facebook.com">Facebook(NOT CLICKED)</a></div> 
 
<div> 
 
    <ul> 
 
    <li><a href="http://youtube.com">Youtube(NOT CLICKED)</a></li> 
 
    </ul> 
 
</div>