两个具有相同ID的元素,要选择一个包含在特定div中的元素 [英] Two elements with the same id, want to select one contained in a specific div

查看:392
本文介绍了两个具有相同ID的元素,要选择一个包含在特定div中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似的东西

 < div id ='container0'> 
< input id ='item0'>
< / div>


< div id ='container1'>
< input id ='item0'>
< / div>

我想选择第二个item0(div container1中的一个),并将其id更改为item1。最好的方法来做到这一点?有没有一种方法可以选择页面上的所有item0,然后检查它们的容器div并确保它与'container1'匹配?



谢谢你的时间。 / p>

解决方案

我知道你没有用jQuery标记 - 但我认为它可能是一个解决方案。那么给每个div一个类,然后用jQuery运行一个each-loop?

 < div id ='container0 'class ='container'> 
< input id ='item0'class ='item'>
< / div>


< div id ='container1'class ='container'>
< input id ='item0'class ='item'>
< / div>

然后,我认为每个循环都可以像这样处理它:

  $('div.container')。each(function(key,value){
var elmid = $(#+ key +div .item).attr('id');
var containerid = $(this).attr('id');

var newelmid = elmid.replace('item',' ');
var newcontainerid = elmid.replace('container','');

if(newelmid!= newcontainerid)
{
$(# + elmid).attr('id','item'+ newcontainerid);
}

});

让我知道这是否与您想要做的相近:)

I have something like this

<div id='container0'>
    <input id='item0'>
</div>


<div id='container1'>
    <input id='item0'>
</div>

I want to select the second item0 (the one in div container1) and change it's id to item1. Best way to do this? Is there a way I can select all item0's on a page and then check their container div and make sure it matches to 'container1'?

Thank you for your time.

解决方案

I know you haven't tagged this with jQuery - but I think it could be a solution. So what about giving every div a class, and then run an each-loop with jQuery?

<div id='container0' class='container'>
    <input id='item0' class='item'>
</div>


<div id='container1' class='container'>
    <input id='item0' class='item'>
</div>

Then I think an each loop could handle it like this:

$('div.container').each(function(key, value) { 
    var elmid = $("#"+key + " div.item).attr('id');
    var containerid = $(this).attr('id');

    var newelmid = elmid.replace('item','');    
    var newcontainerid = elmid.replace('container',''); 

    if(newelmid != newcontainerid)
    {
        $("#"+elmid).attr('id', 'item'+newcontainerid);
    }

});

Let me know if that is anyway near what you want to do :)

这篇关于两个具有相同ID的元素,要选择一个包含在特定div中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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