简体   繁体   English

.prop()和twitter引导模式对话框

[英].prop() and twitter bootstrap modal dialogs

It is recommended to use .prop() instead of .attr() to set disabled property, but I found out that .prop() doesn't work in all cases. 建议使用.prop()而不是.attr()来设置disabled属性,但是我发现.prop()并非在所有情况下都有效。

For example in twitter bootstrap modal windows: http://twitter.github.com/bootstrap/javascript.html#modals 例如在twitter bootstrap模态窗口中: http : //twitter.github.com/bootstrap/javascript.html#modals

Press "Launch demo modal" button and in console run: 按“启动演示模态”按钮,然后在控制台中运行:

$('#myModal .btn').prop('disabled', true);

then the buttons won't be disabled. 那么按钮将不会被禁用。 But if you run: 但是,如果您运行:

$('#myModal .btn').attr('disabled', true);

then they will be disabled successfully. 那么它们将被成功禁用。

Any ideas why it happens? 任何想法为什么会发生?

This question highlights the confusion between .prop() and .attr(). 这个问题突出了.prop()和.attr()之间的混淆。 The .attr() method works directly with the attributes on an HTML element while .prop() works with the JavaScript properties on the underlying JavaScript element. .attr()方法直接与HTML元素上的属性一起使用,而.prop()与基础JavaScript元素上的JavaScript属性一起使用。

For example, while $('#myInput').attr('disabled', true) and $('#myInput').prop('disabled', true) have the same affect, they are actually operating in two very different ways. 例如,虽然$('#myInput').attr('disabled', true)$('#myInput').prop('disabled', true)产生相同的影响,但它们实际上在两个截然不同的地方工作方法。

$('#myInput').attr('disabled', true) would be the equivalent of document.getElementById('myInput').setAttribute('disabled', 'disabled'); $('#myInput').attr('disabled', true)等同于document.getElementById('myInput').setAttribute('disabled', 'disabled');

and $('#myInput').prop('disabled', true) would be the equivalent of document.getElementById('myInput').disabled = true; $('#myInput').prop('disabled', true)等同于document.getElementById('myInput').disabled = true;

While the latter example has the added affect of creating a "disabled" attribute on the element, that is a feature of the disabled property for inputs that is natively handled by the browser. 尽管后面的示例具有在元素上创建“ disabled”属性的附加效果,但这是由浏览器本地处理的输入的disabled属性的功能。

The problem with your example is that you're trying to operate on the anchor elements $('#myModal .btn') which have no native disabled property on their JavaScript objects. 您的示例的问题是,您正在尝试对锚元素$('#myModal .btn')进行操作,这些锚元素的JavaScript对象上没有本机的disabled属性。 Therefore, setting .disabled = true is doing no more than setting .foo = 'bar' . 因此,设置.disabled = true是设置.foo = 'bar'而已。 The browser is not natively going to add an attribute for these elements. 浏览器本身不会为这些元素添加属性。

I hope this makes sense. 我希望这是有道理的。 I will edit later if more clarification is needed. 如果需要更多说明,我将在稍后进行编辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM