简体   繁体   English

动态替换html标签

[英]Dynamically replace html tags

I'm trying to replace some html tags which are being generated by ajax script. 我正在尝试替换一些由ajax脚本生成的html标签。 Ajax script generates the following ul list: Ajax脚本生成以下ul列表:

<ul>
  <li class="odd">some text</li>
  <li class="even">some text</li>
  <li class="odd"><hr /></li>
  <li class="even">some text</li>
</ul>

I need to replace <li class="odd"><hr /></li> with </ul><hr /><ul> . 我需要用</ul><hr /><ul>替换<li class="odd"><hr /></li> </ul><hr /><ul> I guess it has to be some javascript to dynamically replace those tags everytime the list is being generated, but I don't know how to do it exactly. 我想每次生成列表时都必须有一些JavaScript才能动态替换这些标签,但是我不知道该怎么做。 Could you please point me to the right track? 您能指出我正确的方向吗?

Any help is greatly appreciated. 任何帮助是极大的赞赏。

First, you should assign an id to your such that it is easier to access : 首先,您应该为您分配一个ID,以便于访问:

<ul id='myTag'>
    [...]
</ul>

Then, you can use string manipulation and the innerHTML property to do what you want : 然后,您可以使用字符串操作innerHTML属性来执行所需的操作:

var html = document.getElementById('myTag').innerHTML;
document.getElementById('myTag').innerHTML = html.replace('<li class="odd"><hr /></li>', '</ul><hr /><ul>');

You could of course use fancy javascript libraries like jQuery or prototype to do the same, but this is the "roots" way ;) ! 您当然可以使用jQuery或原型之类的精美javascript库来完成此操作,但这是“根”方式;)!

Far out. 远。 Well, (a), make it so you don't need to do that. 好吧,(a),做到这一点,所以您不需要这样做。 :) Or (b): :)或(b):

  1. Get a reference to that ul tag somehow. 以某种方式获得对该ul标签的引用。 give it an id attribute and use: document.getElementById("theULTag") . 给它一个id属性并使用: document.getElementById("theULTag") Or, if it's the first UL tag on the page for example, use document.getElementsByTagName("ul").item(0) 或者,例如,如果它是页面上的第一个UL标签,请使用document.getElementsByTagName("ul").item(0)

  2. Now set a variable equal to this element's innerHtml attribute. 现在设置一个等于该元素的innerHtml属性的变量。 For example: var textToChange = document.getElementById("theULTag").innerHTML 例如: var textToChange = document.getElementById("theULTag").innerHTML

  3. learn about javascript string manipulation here , and do what you need to do. 在此处了解有关javascript字符串操作的信息 ,然后执行您需要做的事情。 (You might need to strip out spaces to make it easier on yourself) (您可能需要删除空间以使其更容易使用)

  4. Put your new text back in with document.getElementById("theULTag").innerHTML = newText 使用document.getElementById("theULTag").innerHTML = newText放回新文本

Good luck! 祝好运!

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

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