创建<按钮>jQuery 忽略 type 属性

发布于 2024-11-27 06:20:56 字数 686 浏览 11 评论 0原文

我正在尝试使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

迟到的我 2024-12-04 06:20:56

你有没有考虑过只是做

 $('<button type="reset" id="reset" name="reset">Reset all fields</button>').appendTo(target);

Have you considered just doing

 $('<button type="reset" id="reset" name="reset">Reset all fields</button>').appendTo(target);
如梦亦如幻 2024-12-04 06:20:56

这不起作用的原因是,一旦创建按钮,HTML 按钮的 type 属性就是只读的。

这意味着您之后无法更改按钮类型,因此,正如 Sam 在他的回答中指出的那样,最好的选择是在创建按钮的同时将类型添加到按钮。

$('<button type="reset"></button>');

如果您在开发时查看错误控制台,您会更快地发现此类错误。

对于您提供的代码,Firefox 错误控制台告诉我们:

Error: uncaught exception: type property can't be changed

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.

$('<button type="reset"></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:

Error: uncaught exception: type property can't be changed
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文