2015-10-16 73 views
1

我有以下结构:如何动态获取html元素的id和?

<input name="20735" class="form-control valid-dateonly error" id="20735" required="" type="text" maxlength="4000" placeholder="" value=""> 
<label class="error" style="left: 0px; white-space: nowrap; position: absolute;" for="20735">This field is required.</label> 
<span class="input-group-addon">    
    <span class="fa fa-calendar"></span> 
</span> 
<div id="div_20735"></div> 

基本上,我有在JQuery $this标签控制。现在基本上我想用id:div_20735来捕捉div。如果您注意到,这个20735也是输入控件的id,它位于标签上方。 我在猜测像$(this).prev().id ...但我没有得到。但我得到这个值(20735),当我做$(this).prev().context.htmlfor ..但我不认为这是检索的最佳方式。 这是我曾尝试:

$('label.error').not('.hide').each(function() { 

    var previousElm = $(this).prev(); 
    if ($(previousElm).hasClass("form-control")) { 

     $("#div_20735").after($(this));//here I need help to capture the id of the div dynamically 

     $(this).css({ 'position': 'absolute', 'white-space': 'nowrap', 'left':'0px' }); 
    }   

}); 

任何帮助,以寻求最佳的方式将高度appretiated。 谢谢。

回答

1

有这是一个尝试 - 它采用for属性值,它是你所需要的

$('label.error').not('.hide').each(function() { 

    var previousElm = $(this).prev(); 
    if ($(previousElm).hasClass("form-control")) { 

     var divID = $(this).attr('for'); 

     $("#div_" + divID).after($(this));//here I need help to capture the id of the div dynamically 

     $(this).css({ 'position': 'absolute', 'white-space': 'nowrap', 'left':'0px' }); 
    }   

}); 
+1

感谢达伦 - 那是在IE工作正常!尽管我更倾向于从输入字段获取ID,而不是标签本身的属性,但我相信它应该适用于所有情况,因为标签本身与输入字段是必需的字段。但我会为更广泛的受众进行测试和确认。 – user2948533

0

$("#div_" + previousElm.attr('name'))应该做的伎俩:

$('label.error').not('.hide').each(function() { 

    var previousElm = $(this).prev(); 
    if ($(previousElm).hasClass("form-control")) { 

     $("#div_" + previousElm.attr('name')).after($(this));//here I need help to capture the id of the div dynamically 

     $(this).css({ 'position': 'absolute', 'white-space': 'nowrap', 'left':'0px' }); 
    }   

});