【发布时间】:2014-11-22 01:15:45
【问题描述】:
以下sn-p中的代码演示了在更改disabled属性后,我无法检索到原始属性值,至少对于disabled属性。 The jQuery docs 暗示 element.getAttribute() 应该能够检索到原始值。
但是,它没有检测到 select 最初没有被禁用。
那么,文档错了吗?布尔属性是否不同?最重要的是,有没有办法在使用prop()更改后获取原始值?
注意 我正在使用 jQuery 1.8.3,它被 Opera 中的 Chromium 37 解释。
$('button').on('click', function() {
var $inputs = $('input, select');
$inputs.each(function() {
var $this = $(this);
var name = $this.prop('name');
console.log('before changing ' + name + '...');
console.log("\tgetAttribute: " + $this[0].getAttribute('disabled'));
console.log("\tprop: " + $this.prop('disabled'));
console.log("\tattr: " + $this.attr('disabled'));
$this.prop('disabled', true);
console.log('after changing ' + name + '...');
console.log("\tgetAttribute: " + $this[0].getAttribute('disabled'));
console.log("\tprop: " + $this.prop('disabled'));
console.log("\tattr: " + $this.attr('disabled'));
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<button>Click</button>
<input name="input" type="text" disabled='disabled' />
<select name="select">
<option>Option</option>
<option>Option</option>
<option>Option</option>
</select>
编辑
不幸的是,.prop() vs .attr() 的问题实际上并没有回答有关禁用之类的布尔属性的问题。考虑一下这个小提琴:http://jsfiddle.net/garreh/uLQXc。它在 1.8.3 下运行良好。现在,考虑这个 fork,它改变了 'disabled' 而不是 'blah':http://jsfiddle.net/wrn1ryjq/1。输入最初未被禁用。更改后,即使 attr 返回“已禁用”。因此, attr 返回原始值的股票答案似乎并不正确。我的问题仍然存在:用 prop 更改后,我如何找出禁用的原始状态?
编辑
嗯,这很尴尬。当然attr() 不会检索原始值。文档说不会。真正的问题是,在使用prop 禁用后,如何从输入中获取禁用的原始值。
不幸的是,根据this comment,这是不可能的:/ 不过感谢您的建议。
【问题讨论】:
标签: javascript jquery prop