jQuery的创建元素 - 另一个.attr()VS .prop()问题 [英] jQuery creating elements - another .attr() vs .prop() question

查看:144
本文介绍了jQuery的创建元素 - 另一个.attr()VS .prop()问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
   .prop()VS .attr()

在新的 .prop() 方法的jQuery ,这是pferred方式向$ p $的创建的特别领域,如一个新元素链接:

Given the new .prop() method in jQuery, which is the preferred way to create a new element with particular fields, e.g. a link:


  1. $('< A>')丙(HREF','...');

  2. $('< A>')。ATTR(HREF','...');

  3. $('< A HREF =...>');

  1. $('<a>').prop('href', '...');
  2. $('<a>').attr('href', '...');
  3. $('<a href="...">');

我一直倾向于使用#2,但目前还不清楚是否的新的的被投的DOM元素不应该现在用1来代替。

I've always tended to use #2, but it's unclear whether a new element being put in the DOM shouldn't now use #1 instead.

推荐答案

我会去与在这种情况下,ATTR()。您正在创建一个新的&LT; A&GT; 元素,并设置其的href HTML属性的,所以它会是有意义的强调。

I would go with attr() in that case. You're creating a new <a> element and setting its href HTML attribute, so it would make sense to emphasize that.

然而,由于的href 属性直接映射到的href DOM属性,使用托()将有完全相同的结果。

However, since the href attribute directly maps to the href DOM property, using prop() would have the exact same result.

让我们再看另一个例子,更相关的ATTR之间的的差异()道具():假设你要设置的&LT的属性; A&GT; 元素,而不是它的的href 。在你的问题的示例code变为:

Let's take another example, more relevant to the differences between attr() and prop(): suppose you want to set the class attribute of the <a> element instead of its href. The sample code in your question becomes:


  1. $('&LT; A&GT;')丙('类名','...');

  2. $('&LT; A&GT;')。ATTR('类','...');

  3. $('&LT;一类=...&GT;');

  1. $('<a>').prop('className', '...');
  2. $('<a>').attr('class', '...');
  3. $('<a class="...">');

IMHO,(2)和(3)使一个人的意图不是更清晰(1)。有不能命名为 A DOM属性,因为该标记可能在宿主语言保留字的事实,充其量是一个实现细节。在 HTML属性通常是我们正在考虑在这方面。

IMHO, (2) and (3) make one's intent clearer than (1). The fact that there cannot be a DOM property named class, because that token might be a reserved word in the host language, is at best an implementation detail. The class HTML attribute is usually what we're thinking about in that context.

当然,在有些情况下则相反,如与工作时布尔HTML属性,如检查禁用。在这种情况下,这将是更健壮设置强类型DOM属性而不是创建不太明确定义的HTML属性的

Of course, there are situations where the opposite is true, e.g. when working with "boolean" HTML attributes like checked or disabled. In that case, it would be more robust to set the strongly-typed DOM property instead of creating the less well-defined HTML attribute.

这篇关于jQuery的创建元素 - 另一个.attr()VS .prop()问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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