简体   繁体   English

onclick innerhtml中的onclick innerhtml

[英]onclick innerhtml in onclick innerhtml

I hope the topic fits the question. 我希望这个话题适合这个问题。

Hey guys excuse my noobness, but I have been cracking my head in trying to solve this problem. 嗨,伙计们,请原谅我,但是我一直在努力解决这个问题。

Code: 码:

<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>

What I wanted it to be is to show a link called "Wonderful" and when clicked it will show "chapter 1" and when "chapter 1" is clicked it will show "Johnss's" 我希望它是显示一个名为“ Wonderful”的链接,单击该链接将显示“第1章”,单击“第1章”时,它将显示“ Johnss's”

I have tried escaping it all with \\ but doesn't work. 我尝试用\\转义,但是不起作用。

If possible I would like it to remain as this method, but if this method doesn't work then is there any method out there. 如果可能的话,我希望它保留为该方法,但是如果该方法不起作用,那么那里还有任何方法。

Ohh and the whole link 哦,整个链接

<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>

is output from php server side to HTML to echo it out. 从php服务器端输出到HTML,以将其回显。 That's why it's in a one line code 这就是为什么它在一行代码中

Thank you 谢谢

Try this 尝试这个

 <!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> 

I would use event handlers and bind the events using js rather than in the html, this way, you can delegate an event for the dynamic object that hasn't been created yet 我将使用事件处理程序,并使用js(而不是html) 绑定事件 ,这样,您可以为尚未创建的动态对象委派事件

 // 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> 

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

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