所以,我知道这已经得到了解答,但之前的答案都没有设法使我的代码工作。我有一个html结构如下:
<div class="form">
<div class="formrow">
<div class="previewcontainer">
<object id="preview">
<object>
</div>
</div>
</div>
我试图将data属性设置为对象,如下所示:
var link = "http://www.someurl.com";
var preview = document.querySelectorAll ("#preview");
preview.setAttribute("data", link);
但是,我得到一个错误preview.setAttribute is not a function
或这个:
var link = "http://www.someurl.com";
var preview = document.getElementById("preview"); //getElementById instead of querySelectorAll
preview.setAttribute("data", link);
确保在创建元素后运行代码,或使用jQuery代码:
$( document ).ready(function() {
}
“未捕获的TypeError:无法读取null的属性'setAttribute'”
通过:LazarusRising-在这种情况下,元素在文档中尚不存在。您需要在创建元素后运行代码,例如在load事件之后或元素下面的脚本。
试试这个:
var link = "http://www.someurl.com";
var preview = document.querySelectorAll ("#preview");
preview[0].setAttribute("data", link);