创建<按钮>jQuery 忽略 type 属性按钮>
我正在尝试使用 jQuery 创建几个按钮,使用如下命令:
$('<button></button>', { type: 'reset', id: 'reset', name: 'reset' })
.text('Reset all fields').appendTo(target);
这工作得很好,只是创建的按钮没有 type
属性。
这就是我想要的:
<button type="reset" id="reset" name="reset">Reset all fields</button>
但我得到了这个:
<button id="reset" name="reset">Reset all fields</button>
即 type="reset"
丢失了。我尝试使用 .attr()
单独添加它,但没有帮助。该属性被简单地忽略。我在这里缺少什么?
我正在使用 jQuery 1.4.4。正如评论中所指出的,这在最新的 jQuery 版本中有效,但这不是我们系统中的版本,我不知道如果我们升级的话可能会破坏什么,所以我更愿意用现有版本来解决这个问题。
I'm trying to create a couple of buttons using jQuery, with commands like this:
$('<button></button>', { type: 'reset', id: 'reset', name: 'reset' })
.text('Reset all fields').appendTo(target);
This works pretty well, except that the buttons are created without the type
attribute.
This is what I want:
<button type="reset" id="reset" name="reset">Reset all fields</button>
but I get this:
<button id="reset" name="reset">Reset all fields</button>
i.e. the type="reset"
is missing. I've tried adding it separately with .attr()
, but it doesn't help. The attribute is simply ignored. What am I missing here?
I'm using jQuery 1.4.4. As noted in comments, this works in the latest jQuery version, but that's not the one in our system and I don't know what things might break if we upgrade, so I'd prefer to solve this with the existing version.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你有没有考虑过只是做
Have you considered just doing
这不起作用的原因是,一旦创建按钮,HTML 按钮的
type
属性就是只读的。这意味着您之后无法更改按钮类型,因此,正如 Sam 在他的回答中指出的那样,最好的选择是在创建按钮的同时将类型添加到按钮。
如果您在开发时查看错误控制台,您会更快地发现此类错误。
对于您提供的代码,Firefox 错误控制台告诉我们:
The reason this doesn't work is that the
type
attribute of a HTML button is read-only once the button is created.This means that you can't change the button type afterwards and so, as Sam pointed out in his answer, your best option is to add the type to the button at the same time as you create the button.
If you look in your Error Console while you're developing you'll catch these kinds of errors much quicker.
For the code you've provided, the Firefox Error Console tells us: