onclick innerhtml中的onclick innerhtml

时间:2018-06-20 08:22:06

标签: javascript html onclick innerhtml

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

伙计们,请原谅我,但是我一直在努力解决这个问题。

代码:

<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章”,单击“ Chapter 1”时,它将显示“ Johnss's”。

我尝试用\进行转义,但是不起作用。

如果可能的话,我希望它保留为该方法,但是如果该方法不起作用,那么那里还有任何方法。

哦,整个链接

<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,以将其回显。这就是为什么它在一行代码中

谢谢

2 个答案:

答案 0 :(得分:1)

尝试一下

Parsing "," ->
 - "", ""
Parsing "foo,bar" ->
 - "foo", "bar"
Parsing "foo,bar;qux,bax" ->
 - "foo", "bar"
 - "qux", "bax"
Parsing "foo,bar;qux,bax;err,;,ful" ->
 - "foo", "bar"
 - "qux", "bax"
 - "err", ""
 - "", "ful"
Parsing "" ->
Failed
Parsing "foo,bar;" ->
 - "foo", "bar"
Remaining unparsed input: ";"
Parsing "foo,bar,qux" ->
 - "foo", "bar"
Remaining unparsed input: ",qux"

答案 1 :(得分:1)

我将使用事件处理程序和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>