jquery之attr与prop方法的区别

在jquery1.6版本之前,如果使用attr方法去设置没有被设置的属性,会返回undefined,在jquery1.6版本之后,为获取并改变DOM的checked、disabled、selected等布尔属性,出现了prop()方法,使用prop方法,如果这三个值没有设置,返回的是false,设置之后返回true。

官方API的说法:

Cross-browser consistency: The values of some attributes are reported inconsistently across browsers, and even across versions of a single browser. The .attr() method reduces such inconsistencies.

prop()方法与attr()方法用法一致,语法如下:

1. attr(name,value)

栗子:

$(function() {

        // 设置单个属性
      $("img").attr("alt","头破了");
      $("img").attr("title","错错错");

        // 设置多个属性
        $("img").attr({
            alt: "头破了";
            title: "错错错"
})
    });

2. prop(name,value)

栗子:

$(function () {
    $("input").eq(0).click(function () {
      $("#ck").prop("checked", true);
    });
});

猜你喜欢

转载自blog.csdn.net/line233/article/details/84231541
今日推荐