为什么所有陈述都不能取代?

时间:2017-11-07 22:05:32

标签: javascript html

我想用这些代码替换语句。 这是我的HTML代码:

<p id="mytxt" >**SC-start**<br/>This is a code<br/>**SC-end**</p>
<p id="mytxt" >**SC-start**<br/>This is a code<br/>**SC-end**</p>
<p id="mytxt" >**SC-start**<br/>This is a code<br/>**SC-end**</p>

<button onclick="replacewords()" >Show This</button>

这是我的Javascript代码:

function replacewords() { 
    var curs = document.querySelectorAll("#mytxt");

    for (var i = 0 ; i <= curs.length ; i++ ) {
    var str = curs[i].innerHTML;
    var str0 = str.replace("**SC-start**" , "<pre>");
    var str1 = str0.replace("<br>" , "");
    var endstr = str1.replace("**SC-end**" , "</pre>");
    document.getElementById("mytxt").innerHTML = endstr ; 
}
}

2 个答案:

答案 0 :(得分:0)

将每个id中的p替换为class,因为id仅适用于唯一元素,而class可以代表多个元素。然后,将其放入您的代码中:

function replacewords() {
    var mytxt = document.getElementsByClassName("mytxt");
    for (var i = 0 ; i <= mytxt.length ; i++ ) {
        var str = mytxt[i].innerHTML;
        var str0 = str.replace("**SC-start**" , "<pre>");
        var str1 = str0.replace("<br>" , "");
        var endstr = str1.replace("**SC-end**" , "</pre>");
        mytxt[i].innerHTML = endstr; 
    }
}
<p class="mytxt" >**SC-start**<br/>This is a code<br/>**SC-end**</p>
<p class="mytxt" >**SC-start**<br/>This is a code<br/>**SC-end**</p>
<p class="mytxt" >**SC-start**<br/>This is a code<br/>**SC-end**</p>

<button onclick="replacewords()" >Show This</button>

答案 1 :(得分:0)

首先在你的html中替换class的id属性。 然后,在你的javascript中使用curs [i] .innerHTML

function replacewords() { 
  var curs = document.querySelectorAll(".mytxt");
  for (var i = 0 ; i <= curs.length ; i++ ) {
    var str = curs[i].innerHTML;
    var str0 = str.replace("**SC-start**" , "<pre>");
    var str1 = str0.replace("<br>" , "");
    var endstr = str1.replace("**SC-end**" , "</pre>");
    curs[i].innerHTML = endstr ; 
  }
}

http://jsbin.com/sobasugovu/edit?js