我有基于id属性的工作脚本。因为我有很多问题,所以决定在jQuery中使用class属性。但是我没有成功使用以下脚本(我不擅长编写脚本:()
如果你的专家可以建议我更好的方式,那就太好了。我有300多个单词用符号替换(大约200页)。
非常感谢。
HTML代码
<script src="http://code.jquery.com/jquery-latest.js"></script>
<input type="submit" name="replace" id="replace" value="Replace" />
<div class="my_div">Default content</div>
<div class="my_div">Default content 2</div>
java脚本
$('#replace').click(function() {
var str=document.getElementByClassName("my_div").innerHTML;
var n=str.replace("default","somesymbol");
var n=str.replace("content","somesymbol");
var n=str.replace("im","somesymbol");
document.getElementByClassName("my_div").innerHTML=n;
}
答案 0 :(得分:2)
使用类似的东西:
$('#replace').click(function() {
$('.my_div').each(function() {
var $this = $(this);
var html = $this.html();
$this.html(html.replace(/default|content|im/gi, 'somesymbol'));
});
});
getElementByClassName
应该是getElementsByClassName
,它会返回您必须迭代的NodeList
。
此外,如果您不需要保留替代格式(例如foo <b>bar</b>
),请使用.text()
代替.html()
。
答案 1 :(得分:0)
使用jQuery html()
方法如果使用函数作为参数,它将使用类名循环遍历整个元素集合,自动让您访问现有的html并在返回html string时替换它/ p>
$('#replace').click(function() {
$('.my_div').html(function( idx, oldHtml){
/* if you need access to other properties or attributes of element -"this" or "$(this)" within this function*/
return oldHtml.replace(/default|content|im/gi, 'somesymbol');
});
});
参考:http://api.jquery.com/html/
向下查看在jQuery 1.4版中添加的API页面