在两个div元素中具有相同id的两个元素与其他id是否正常? [英] Is it normal to have two elements with same id in two div elements with other id?

查看:190
本文介绍了在两个div元素中具有相同id的两个元素与其他id是否正常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,两个元素不能拥有相同的id。但是发生这样,在我的项目中我有两个元素在其他div中具有相同的id,例如

 < div id =div1> 
< img id =loading/>
< / div>
< div id =div2>
< img id =loading/>
< / div>

和css:

 #div1 #loading 
{
some style here ...
}
#div2 #loading
{
...
}

对我来说工作正常,但也许不推荐做


$ b



是的,我知道,我可以使用类,它强烈推荐做这样,但我想知道在这种使用id有任何潜在的风险吗?
i认为没有,因为我写的例子



$(#div1 #loading)... 它变成一个独特的元素。
不是吗?

解决方案

将您的id更改为类。提供重复ID不是一个好主意。



认为两个同学在同一班上没有。想象他们得到考试结果。



您的方式不是跨浏览器兼容的,并且在编码JavaScript时会影响很多,并且发布表单等



您可以使用

类别获得相同的效果

请参阅

 < div id =div1> 
< img class =loading/>
< / div>
< div id =div2>
< img class =loading/>
< / div>

和css:

 #div1 .loading 
{
some style here ...
}
#div2 .loading
{
...
}


i know, that two elements can't hav the same id. But it's happens so, that in my project i have two elements with same id in other divs, like this

<div id="div1">
     <img id="loading" />
</div>
<div id="div2">
     <img id="loading" />
</div>

and css:

#div1 #loading
{
    some style here...
}
#div2 #loading
{
    another style here...
}

works fine for me, but maybe it is not reccomended to do by so?

Thanks

UPDATE

Yes, i know, thet i can use classes, and it's strongly recomended to do by so, but i want to know is there any potential risk in this usage of id? i think no, becouse when i wrote for example

$("#div1 #loading")... it becomes a unique element. isn't it?

解决方案

Change your id to class. It is not a good idea to give duplicate id.

Think two students having same roll no in a class. Imagine them getting examination result. How will the school be able to recognise the marksheet?

Your way is not cross browser compatible, and will affect a lot while coding JavaScript, and posted form etc

You can get the same effect using class

see

<div id="div1">
     <img class="loading" />
</div>
<div id="div2">
     <img class="loading" />
</div>

and css:

#div1 .loading
{
    some style here...
}
#div2 .loading
{
    another style here...
}

这篇关于在两个div元素中具有相同id的两个元素与其他id是否正常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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