gpt4 book ai didi

javascript - 如何动态获取html元素的id?

转载 作者:行者123 更新时间:2023-11-28 16:46:00 26 4
gpt4 key购买 nike

我有以下结构:

<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...但我没有得到。但是当我执行 $(this) 时,我得到了这个值(20735) .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' });
}

});

任何帮助找到最佳方法的人都将受到高度赞赏。谢谢。

最佳答案

试一试 - 它采用 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' });
}

});

关于javascript - 如何动态获取html元素的id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33168986/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com