将对象设置为jquery中attr()方法的值

Setting object as value to attr() method in jquery

本文关键字:方法 attr 对象 设置 jquery      更新时间:2023-09-26

我使用$.data()函数设置div的大小:

function init() {
    comp = $("#center");
    comp.data('image', {
        dimensions : {
            width : comp.width(),
            height : comp.height(),
            x0 : comp.position().left,
            y0 : comp.position().top,           
        }
    });
}

我正在检索如下值:

var image = comp.data('image');
alert(image.dimensions.x1);

代码很好,它也在工作。我想知道是否可以通过$.attr()功能来实现,哪种方式会更好。

您可以像这样轻松处理:

var values = {width: '100px', height: '100px'};
$('#id-of-your-img').css(values);

您可以尝试attr("style","),但我更喜欢使用css()进行css操作。请参见此处:http://api.jquery.com/css/

这里有一个例子,有人添加了一个函数来创建具有一些额外功能的类似行为。

小提琴

// dispatch to data() and attr()
$.fn.dataAttr = function(key, value) {
    var $this = this,
        ret = this.data(key, value);
    if (typeof key == "object") {
        $.each(key, function(key, value) {
            $this.attr("data-" + jQuery.uncamelCase(key), typeof value in {string:1, number:1} ? value : '~defined~');
        });
    } else if (value !== undefined) {
        $this.attr("data-" + jQuery.uncamelCase(key), typeof value in {string:1, number:1} ? value : '~defined~');
    }
    return ret;
};