声明
使用jquery,如果您有一个定义如下的按钮元素:<button value="123">456</button>
如果您使用 .attr('value');
或 .val();
,浏览器将为您提供不同的值
<button>
元素就是 <input type="button">
的简写形式。
设置 <input type="button">
值的方法是设置 value="Click Me"
因此 <input type="button" value="Click Me">
与 <button>Click Me</button>
相同。
为什么使用
.val()
在不同的浏览器上返回不同的值。谁是正确的?Firefox:
123 | .val() = 123 |显示文本 = 456
Chrome:
123 | .val() = 123 |显示文本 = 456
>= Internet Explorer 8:
123 | .val() = 123 |显示文本 = 456
<= Internet Explorer 7:
456 | .val() = 456 |显示文本 = 456
最佳答案
阅读 w3 specification 后,我相信 Chrome 和 Firefox 是正确的。具体是因为这个片段:
Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content.
W3 规范将 <button></button>
标记之间找到的信息称为内容,而不是值,这就是我的观察结果。另一个提示是 Internet Explorer 是唯一返回不同值的浏览器,而且我相当肯定 Internet Explorer 是宇宙中所有痛苦的根源。
我还决定在 Mac 上测试 Safari 5、Opera、Chrome 和 Firefox 3.6.8。全部返回 456 作为显示的文本,并返回 123 作为 .val()
关于Jquery .val() 浏览器差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3664367/