如何提单行所有属性:)如何提单行所有属性
document.getElementById("image").src = "landscape.jpg";
document.getElementById("image").width = "300";
document.getElementById("image").height = "300";
如何提单行所有属性:)如何提单行所有属性
document.getElementById("image").src = "landscape.jpg";
document.getElementById("image").width = "300";
document.getElementById("image").height = "300";
你不能做到这一点的一条线,用JavaScript;你可以,不过,缩写为:
document.getElementById("image").src = "http://lorempixel.com/200/200/nightlife/3";
document.getElementById("image").width = document.getElementById("image").height = "300";
虽然,说实话,我不知道你有什么收获。
当然,如果你选择的效率(尽管是微优化),你回去三条线再次通过缓存的document.getElementById()
结果:
var image = document.getElementById('image');
image.src = "http://lorempixel.com/200/200/nightlife/3";
image.width = image.height = "300";
很可能在大部分,如果不是所有,浏览器使用浏览器分配AUTOMAGIC全局变量,对一个元素的引用与id
属性映射到(该名称的变量,id="image"
元素可用一个全局变量image
)下:
image.src = "http://lorempixel.com/200/200/nightlife/3";
image.width = image.height = "300";
JS Fiddle demo。但是,值得注意的是,尽管automagic变量是可能的,但它们的使用并不可取:全局变量,特别是在大型代码库或多个贡献者中,容易出现错误和误用。而且,正如下面的评论所指出的那样,它们的使用是或可能会被弃用(参考:Do DOM tree elements with ids become global variables?)。
<img src="" id="image" />
用途:
上述所有与下面的HTML中使用
with(document.getElementById("image")) { src = "landscape.jpg"; width = "300"; height = "300"; }
或者使用jQuery:
$("#image").attr("src", "landscape.jpg").width(300).height(300);
// or
$("#image").attr("src", "landscape.jpg").attr("width": "300").attr("height": "300");
// or
$("#image").attr("src", "landscape.jpg").css({ "width": "300px", "height": "300px" });
不要建议使用'with'。除了其他问题之外,它在严格模式下不受支持。此外,没有提及jQuery或指定jQuery标记的问题不应使用jQuery解决方案来回答,除非已经通过评论确认了他或她可以使用jQuery方法。 – 2014-10-29 07:54:20
还可以保存一个变量的白色元素,所以你不必每次都做document.getElementById
var img = document.getElementById("image");
img.src = "landscape.jpg";
img.width = img.height = "300";
你也可以做一个功能能够在一条线以后
function setValues(element, props){
for(var key in props){
element[key] = props[key];
}
}
setValues(document.getElementById("image"), {src: "landscape.jpg", width:"300", height:"300"});
如果你需要做大量的DOM操作,你可以看看像jQuery和仄一个框架,但如果这是你需要改变的唯一的东西,这会变得矫枉过正。
不同意建议使用“automagic全局变量”。这种用法被广泛弃用。请参阅http://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables。 – 2014-10-29 07:52:12
不要误解我,我提到的可能性是*不*我推荐的做法;我很高兴看到这种可能性的后面。 – 2014-10-29 07:53:47