我想只用JavaScript来加载iframe
,到目前为止,我一直在使用这样的:在没有jQuery的div上加载html?
$(".punctis-social-box").html("<iframe></iframe>");
但因为它是唯一的指令,我有一个使用jQuery的,我会喜欢不依赖于任何更多在jQuery上。
我想只用JavaScript来加载iframe
,到目前为止,我一直在使用这样的:在没有jQuery的div上加载html?
$(".punctis-social-box").html("<iframe></iframe>");
但因为它是唯一的指令,我有一个使用jQuery的,我会喜欢不依赖于任何更多在jQuery上。
也许不是最好的方式开始:
var elements = document.getElementsByClassName("punctis-social-box");
for (var i = 0; i < elements.length; i++) {
elements[i].innerHTML = "<iframe></iframe>";
}
或者使用querySelectorAll
:
var elements = document.querySelectorAll(".punctis-social-box");
for (var i = 0; i < elements.length; i++) {
elements[i].innerHTML = "<iframe></iframe>";
}
为了避免所有陋习TM你可以使用document.createElement
,而不是明确的变化内部HTML:
var element = document.querySelector(".punctis-social-box"),
iframe = document.createElement("iframe");
while (element.firstChild) { // the fastest way
element.removeChild(element.firstChild); // to clear the contents
}
element.appendChild(iframe); // adding new <iframe>
方法1:
var social_boxes = document.getElementsByClassName('punctis-social-box');
social_boxes[0].innerHTML += '<iframe></iframe>'; // add to first element, loop thru "social_boxes" if you want to add iframe to all elements
方法2(越好):
var social_boxes = document.getElementsByClassName('punctis-social-box');
var iframe = document.createElement('iframe');
social_boxes[0].appendChild(iframe); // add to first element, loop thru "social_boxes" if you want to add iframe to all elements
没有'getByClassName'方法在JavaScript中。 – VisioN
@VisioN是的,有,但它不是标准的,直到HTML5(虽然FF已经有它自第3版以来),如果你想要兼容性,你将不得不使用nastier方法。 – DaveRandom
@DaveRandom我找不到任何地方... –
没有提到身体阿贾克斯... – DomingoSL
@Amadan我删除了我的评论,我显然误解了这个问题:) –