使用jquery更改iframe属性 [英] Change iframe attribute with jquery
问题描述
我有类似的东西:
<iframe id="frame" width="200" height="150"
src="http://www.youtube.com/embed/GiZGEFBGgKU?rel=0&
amp&iv_load_policy=3;autoplay=1" frameborder="0" allowfullscreen></iframe>
我想尝试使用jquery更改宽度和高度:
And I want to change the width and height using jquery I try:
$("#frame").setAttribute("width", "50");
$("iframe").setAttribute("width", "31");
它们都不起作用
推荐答案
正如Sarfraz已经指出的那样,为jquery选择器对象设置属性的正确方法是使用 attr(attrName,attrVal)
。 setAttribute
不起作用的原因值得解释,因为我不止一次地反对这一点:
As Sarfraz already pointed out, the correct way to set the attribute for a jquery selector object is by using the attr("attrName", "attrVal")
. The reason the setAttribute
didn't work is something worth explaining, as I've hit my head against this point on more than one occasion:
当你使用jquery的选择器语法时,它返回一个在jquery中定义的对象 - 它本质上是选择器匹配的所有元素的列表。无论它是匹配一个元素(应该始终是id选择器的情况)还是多个,返回的对象是元素列表,从不是单个DOM对象(例如单个元素)。 setAttribute
是实际 HTMLElement
对象的方法。
When you use jquery's selector syntax, it returns an object -- defined in jquery -- which is essentially a list of all of the elements that the selector matched. Whether it matches one element (which should always be the case with an id selector) or more than one, the returned object is the element list, never a single DOM object (eg single element). setAttribute
is a method for actual HTMLElement
objects.
这就是为什么
$("#frame")[0].setAttribute("width", "200");
有效,但
$("#frame").setAttribute("width", "200");
没有。 jquery元素没有该方法,即使其列表中的 HTMLElement
对象也有。
does not. The jquery element does not have that method, even though the HTMLElement
objects in its list do.
如果你想要(无论出于何种原因)使用原生 HTMLElement
方法(或者选择器返回的元素共有的方法,如输入等),你可以使用jquery的 each()
方法,如下所示:
If you wanted to (for whatever reason) use a native HTMLElement
method (or a method common to the elements your selector returns, such as inputs, etc), you can use jquery's each()
method, like so:
// Set all iframes to width of 250
$("iframe").each(
function(index, elem) {
elem.setAttribute("width","250");
}
);
每个()
方法的回调可以是传递了两个可选参数,第一个是选择器列表中元素的索引,第二个是实际DOM元素,您可以调用本机DOM方法。
The each()
method's callback can be passed two optional parameters, the first being the index of the element in the selector list, the second being the actual DOM element, which you can call native DOM methods on.
就像我说的那样,我真的很沮丧,试图弄清楚如何不止一次地使用本机方法使用jquery的选择器结果,所以我希望这有助于清除为什么 setAttribute()
不起作用,但一般是本机方法,以及当你找不到jquery等效时如何实际让它们工作。
Like I said, I've gotten really frustrated trying to figure out how to use jquery's selector results with native methods more than once, so I hope this helps clear up not only why setAttribute()
doesn't work, but native methods in general, and how to actually get them to work when you can't find the jquery equivalent.
这篇关于使用jquery更改iframe属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!