如何使用jQuery更改属性? [英] How to change a attributes with jQuery?

查看:73
本文介绍了如何使用jQuery更改属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个3rd party脚本,它在图像上设置宽度和高度,但是对于我一生来说,我不知道它是如何工作的.可能来自数据库或类,但是有很多.

I have a 3rd party script which is setting a width and height on images, but for the life of me I can't figure out how it's doing it. It's probably from the database or a class but there are a lot of them.

HTML看起来像这样:

The HTML looks something like this:

<img src="..." width="30px" height="30px">

使用jQuery,如何更改高度和宽度值?

Using jQuery, how can I change the height and width values?

我猜是这样的:

$("..[$width="]").replace(

这是元素的HTML:

<div id="prodThumbnails">
<table style="width: 641px;">
<tbody>
<tr>
<td align="right" style="vertical-align: middle;">  
</td>   
<td nowrap="nowrap" class="productPhotoThumbnailSection">
<a onclick="javascript:drawMainImage('0', '')" href="javascript:swapImage()">
<img height="30" width="30" border="0" title="" alt="" 
src="images/products/85.png"/></a>
     
<a onclick="javascript:drawMainImage('1', '')" href="javascript:swapImage()"><img height="30" width="30" border="0" title="" alt="" 
src="images/products/90.jpg"/></a>
     
<a onclick="javascript:drawMainImage('2', '')" href="javascript:swapImage()">
<img height="30" width="30" border="0" title="" alt="" src="images/products/92.jpg"/></a>
</td>
<td align="left" style="vertical-align: middle;">
</td>
</tr>
</tbody>
</table>
</div>

我尝试这样做:

$(function() {
   $("td.productPhotoThumbnailSection img").attr("width","64px");
   $("td.productPhotoThumbnailSection img").attr("height","64px");

  });

但是它一直将图像的宽度和高度设置为0.

but it keeps setting the image width and heights to 0.

推荐答案

因此,您要为元素的widthheight 属性设置一个新值吗?您可以使用 attr() 函数来做到这一点.

Thus, you want to set a new value for the width and height attributes of the element? You can do that with the attr() function.

基本示例:

element.attr('width', '100');
element.attr('height', '100');

或链接:

element.attr('width', '100').attr('height', '100');

或一次全部:

element.attr({
    width: '100',
    height: '100'
});

例如,在element中的$('img')可以获取所有<img>元素,或者$('#imgId')可以获取特定的<img id="imgId">元素.请参阅 jQuery选择器部分,以了解有关选择元素的更多信息.

Where in element can be for example $('img') to get all <img> elements, or $('#imgId') to get the specific <img id="imgId"> element. See the jQuery Selectors section to learn more about selecting elements.

作为对编辑的响应,毕竟您不需要widthheight属性中的'px'后缀,它们已经隐含地以像素为单位.当您要更改关联的CSS属性(例如element.css('width', '100px');)时,仅需要'px'.我已经相应更新了答案.

as response on your edit, after all you don't need the 'px' suffix in the width and height attributes, they are implicitly already in pixels. You only need the 'px' when you want to change the associated CSS properties such as element.css('width', '100px');. I've updated my answer accordingly.

这篇关于如何使用jQuery更改属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆