简体   繁体   English

在setTimeout之后动态创建的锚不起作用

[英]Dynamically created anchor doesn't work after setTimeout

Hi I make a Timer with Javascript, it works fine. 嗨,我用Java做一个Timer,它工作正常。 And when it finish the 5 seconds count the code enable a target for open a web, but when I click its dont working. 当完成5秒钟时,该代码会启用一个目标来打开网络,但是当我单击它时,它就不起作用了。 I try this code outside the timer and its works perfectly. 我在计时器之外尝试了此代码,它的工作原理非常完美。 What is the error? 有什么错误?

<?php
$windowsOpen .= "window.open('$value', '_blank');";
?>

<script type="text/javascript">
function countDown(secs,elem){
var element = document.getElementById(elem);
element.innerHTML = "Please wait for "+secs+" seconds";
if(secs < 1){
    clearTimeout(timer);
    element.innerHTML='<p><a href="#" onclick="<?= $windowsOpen; ?>">Click to open webs</a></p>';
}
secs--;
var timer = setTimeout('countDown('+secs+',"'+elem+'")',1000);
}
</script>
<div id="status"></div>
<script type="text/javascript">countDown(5,"status");</script>

Inline event handlers are essentially eval inside HTML markup - they're bad practice and result in poorly factored, hard-to-manage code. 内联事件处理程序本质上是在HTML标记内部的eval-这是一种不好的做法,并且会导致分解不良,难以管理的代码。 Seriously consider attaching your events with JavaScript, instead: developer.mozilla.org/en/DOM/element.addEventListener 认真考虑使用JavaScript附加事件,而不是:developer.mozilla.org/en/DOM/element.addEventListener

If you absolutely need the window opener to be handled with Javascript instead of the browser's nice native behavior, then define the URL you want people to navigate to upfront, and then attach a listener to the element when it's created: 如果您绝对需要用Javascript处理开窗器而不是浏览器的良好本机行为,则定义要让人们预先导航的URL,然后在创建元素时将侦听器附加到该元素:

<?php
$url = 'https://www.google.com';
?>

<script type="text/javascript">
var url = '<?=$url;?>';
var timer;
function countDown(secs,elem){
  var element = document.getElementById(elem);
  element.innerHTML = "Please wait for "+secs+" seconds";
  if(secs < 1){
    element.innerHTML='<p><a href="#">Click to open link</a></p>';
    element.querySelector('a')
      .addEventListener('click', () => {
        window.open(url);
      });
  } else {
    secs--;
    setTimeout(countDown, 1000, secs, elem);
  }
}
</script>
<div id="status"></div>
<script type="text/javascript">countDown(5,"status");</script>

You should also avoid using eval in your setTimeout - always write out functions in normal JS, rather than as strings to be parsed into functions. 你也应该避免使用eval在你setTimeout -总是写出功能正常JS,而不是作为字符串被解析成功能。

But it would be much less user-unfriendly if you would let them click the link themselves, using the browser's normal behavior: 但是,如果让他们使用浏览器的正常行为自己单击链接,则对用户的友好程度将大大降低:

element.innerHTML='<p><a href="#">Click to open link</a></p>';
element.querySelector('a')
  .href = url;

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM