【问题标题】:onclick innerhtml in onclick innerhtmlonclick innerhtml 在 onclick innerhtml
【发布时间】:2023-03-11 23:49:01
【问题描述】:

我希望这个话题适合这个问题。

大家好,请原谅我的菜鸟,但我一直在努力解决这个问题。

代码:

<a id="123" href="#123" onclick="document.getElementById('chgtext').innerHTML='<a id="1" href="#" onclick="document.getElementById('chgtext_1').innerHTML='Johnss's House';">chapter 1</a>';">Wonderful</a>

<div id="chgtext"> </div>
<div id="chgtext_1"> </div>

我希望它显示一个名为“Wonderful”的链接,点击它会显示“第 1 章”,点击“第 1 章”时会显示“Johnss”

我尝试使用\ 转义这一切,但不起作用。

如果可能的话,我希望它保持这种方法,但如果这种方法不起作用,那么有什么方法吗。

哦,还有整个链接

<a id="123" href="#123" onclick="document.getElementById('chgtext').innerHTML='<a id="1" href="#" onclick="document.getElementById('chgtext_1').innerHTML='Johnss's House';">chapter 1</a>';">Wonderful</a>

是从 php 服务器端输出到 HTML 以将其回显。这就是为什么它在一行代码中

谢谢

【问题讨论】:

  • 尝试使用 Javascript 而不是 HTML 属性正确附加您的处理程序,您的代码将更容易阅读和调试。

标签: javascript html onclick innerhtml


【解决方案1】:

试试这个

<!DOCTYPE html>
<html>
<body>
<a href="#" onclick="main()">Wonderful</a>
<p id="main"></p>
<p id="sub"></p>
<script>
function main(){
document.getElementById("main").innerHTML =
"<a href='#' onclick='sub()'>Chapter 1</a>";
}
function sub(){
document.getElementById("sub").innerHTML =
"Johnss's";
}
</script>
</body>
</html>

【讨论】:

    【解决方案2】:

    我会使用事件处理程序和bind the events using js而不是在html中,这样,您可以delegate an event为尚未创建的动态对象

    // bind a normal event to the first link:
    var link = document.getElementById('123');
    
    link.addEventListener('click', function (e) {
       e.preventDefault();  // as the target is a link you want to prevent the default action of it 
       document.getElementById('chgtext').innerHTML = '<a id="1" href="#">chapter 1</a>';
    });
    
    // the following is a delegated event - you bind it to an existing element (in this case the document) and then check that the target being clicked is the new element that has been dynamically created
    
    document.addEventListener('click', function (e) {
      
      // check the id of the clicked element
      if (e.target.id == 1) { 
        e.preventDefault();  // as the target is a link you want to prevent the default action of it 
        document.getElementById('chgtext_1').innerHTML = 'Johns\'s House';
      }
    });
    <a id="123" href="#123">Wonderful</a>
    
    <div id="chgtext"> </div>
    <div id="chgtext_1"> </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 2023-04-03
      • 2013-02-17
      • 1970-01-01
      相关资源
      最近更新 更多