首先,对不起,我对javascript不好。
HTML:
<div id="Comment-ID">
<p class="Comment-class">...</p>
<p class="Comment-class">...</p>
<p class="Comment-class">...</p>
<p class="Comment-class">...</p>
</div>
Javascript:
<script type='text/javascript'>
function autoloadmore() {
var loadmoreClass = document.getElementsByClassName("loadmore")[0];
var loadmoreChild = loadmoreClass.querySelector('a')
if (loadmoreClass) {
loadmoreChild.click();
}
}
//<![CDATA[
function InsertarImagenVideo(id) {
var IDelemento = document.getElementById(id),
sustituir = IDelemento.innerHTML;
sustituir = sustituir.replace(/\[img\](.[^\]]*)\[\/img\]/ig, "<img class='img-comentarios' src='$1'\/>");
document.getElementById(id).innerHTML = sustituir;
}
//]]>
window.onload = function() {
autoloadmore();
setTimeout(function(){
InsertarImagenVideo('Comment-ID');
},3000);
};
</script>
InsertarImagenVideo
用图像替换其中的一些文本。我想使用Comment-ID
来定位p
元素内的内容,而不是Comment-class
。
注意:HTML不能更改。
有人可以帮我吗?
答案 0 :(得分:1)
您必须使用循环来获取所有元素以进行修改。如果您的代码使用 id 起作用,则以下代码应该起作用:
function InsertarImagenVideo(myClass) {
var ClassElemenTo = [].slice.call(document.querySelectorAll(myClass));
ClassElemenTo.forEach(function(el){
var sustituir = el.innerHTML;
sustituir = sustituir.replace(/\[img\](.[^\]]*)\[\/img\]/ig, "<img class='img-comentarios' src='$1'\/>");
el.innerHTML = sustituir;
});
}
并通过在类名前加上点(.
)来调用函数:
InsertarImagenVideo('.Comment-class');
答案 1 :(得分:1)
您必须使用类似document.getElementsByClassName
的函数,该函数返回一个数组,而不是单个值。要处理数组的所有元素以进行修改,您必须使用循环:
function InsertarImagenVideoByClass(className) {
var elements = document.querySelectorAll(className);
Array.prototype.forEach.call(elements, function(element) {
sustituir = element.innerHTML;
sustituir = sustituir.replace(/\[img\](.[^\]]*)\[\/img\]/ig, "<img class='img-comentarios' src='$1'\/>");
element.innerHTML = sustituir;
});
}
window.onload = function() {
autoloadmore();
setTimeout(function() {
InsertarImagenVideo('.Comment-class');
}, 3000);
};
答案 2 :(得分:1)
function InsertarImagenVideoByClass(class) {
var IDelementos = document.querySelectorAll(className);
Array.prototype.forEach.call(elements, function(element) {
sustituir = element.innerHTML;
sustituir = sustituir.replace(/\[img\](.[^\]]*)\[\/img\]/ig, "<img class='img-comentarios' src='$1'\/>");
element.innerHTML = sustituir;
}
}
window.onload = function() {
autoloadmore();
setTimeout(function() {
InsertarImagenVideo('.Comment-class');
}, 3000);
};
答案 3 :(得分:1)
只需更改您的InsertarImagenVideo
函数即可查找类。
function InsertarImagenVideo(className) {
if (!className) { console.error('Class name is mandatory.'); return; }
var classElements = document.querySelectorAll(className);
Array.prototype.forEach.call(classElements, function(el){
var sustituir = el.innerHTML;
sustituir = sustituir.replace(/\[img\](.[^\]]*)\[\/img\]/ig, "<img class='img-comentarios' src='$1'\/>");
el.innerHTML = sustituir;
});
}
请注意,请改用.forEach.call,因为返回的集合不是常规集合,而是NodeList
。
并调用传递类名的函数
InsertarImagenVideo('Comment-class');