有没有正确的方法来重用Id? [英] Is there any proper way to reuse Id's?

查看:74
本文介绍了有没有正确的方法来重用Id?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 bootstrap的模态中有一个创建表单。与该表单相关的所有 Javascript 都使用 id 而不是。现在我要做的是创建第二个表单,它使用相同的 Javascript (基于之前所说的id) )。有没有适当的方法来实现这一目标?我知道使用dublicate id是一种非常糟糕的做法。

I have a "create" form inside a bootstrap's modal. All my Javascript related with that form uses id's and not classes. Now what i want to do is to create a second form that uses the same Javascript (based on id's as said before). Is there any proper way to achieve that? I know that is a very bad practice to use dublicate id's.

推荐答案

不是真的,没有。

当您使用ID时,您在页面上告诉浏览器该ID是唯一可用的。

When you use IDs, you're telling the browser that the ID is uniquely available, on the page.

如果您有两个表单具有相同的ID,这意味着您已经破坏了该保证。

If you have two forms with the same IDs, that means you've broken that guarantee.

这会导致问题的一个示例是 document.getElementById()
它将获取它找到的第一个元素。
如果有两个,它只会给你第一个。

An example of where this causes problems is document.getElementById( ). It will grab the first element it finds. If there are two, it will only get you the first one.

另一个问题:带有ID的
表格习惯被保存到窗口,使用该ID(这种行为不是每个浏览器的100%标准,使用率超过2%,全球,今天,但它仍然很常见)。

Another issue: forms with IDs have a habit of being saved to Window, using that ID (this behaviour isn't 100% standard across every browser with more than 2% usage, globally, today, but it's still pretty common).

我在这个领域看过的丑陋的解决方案就像my-id-1my-id-2等等,你可以在那里访问它们喜欢: document.getElementById(my-id-+ x);

Ugly solutions I've seen in this space are things like "my-id-1" "my-id-2", et cetera, where you then access them like: document.getElementById("my-id-" + x);

...真的不漂亮完全...

...really not pretty at all...

...或者,当你想来回切换时,你可以将表格保存在JS中,并将它们附加到页面上。
通过这种方式,他们可以共享ID,只要它们不会同时附加到页面上。

...alternatively, you can keep the forms in JS, and just attach them to the page, when you want to switch back and forth. In this way, they can share IDs, so long as they're never attached to the page at the same time.

document.querySelector("#my-form") === form1; // true
form1.parentNode.replaceChild(form2, form1);
document.querySelector("#my-form") === form2; // true

同样,这不会帮助您使用内置表单和输入命名空间,以任何有意义的方式,但如果这是一个你100%忽略的功能(不是坏事),这将解决这些问题。

Again, this isn't going to help you with the built-in form and input namespacing, in any meaningful way, but if that's a feature you are 100% ignoring (not a bad thing to do), this will solve those problems.

或者,你可以只移动到类和数据属性(或只是属性),生活会变得更容易......

Alternatively, you could just move to classes and data-attributes (or just attributes), and life would get easier still...

这篇关于有没有正确的方法来重用Id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆