jQuery 动态选择器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1230753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:58:14  来源:igfitidea点击:

jQuery dynamic selector

jquery

提问by Devin Ceartas

I have some code which uses a selector in a loop.

我有一些代码在循环中使用选择器。

This works:

这有效:

document.getElementById("new_grouping_"+i).value

This does not: $("#new_grouping_"+i).value

这不会: $("#new_grouping_"+i).value

Is there a way to do this using jQuery?

有没有办法使用 jQuery 做到这一点?

回答by CMS

You should use the val()function:

您应该使用val()函数:

var myValue = $("#new_grouping_"+i).val(); // to get the value

$("#new_grouping_"+i).val("something");    // to set the value 

回答by Tyler Carter

$("#new_grouping_"+i).val()gets you the value of a form.
$("#new_grouping_"+i).text()gets you the text of an html element.
$("#new_grouping_"+i).html()gets you the html of an html element.

$("#new_grouping_"+i).val()为您提供表单的价值。
$("#new_grouping_"+i).text()获取 html 元素的文本。
$("#new_grouping_"+i).html()获取 html 元素的 html。

$("#new_grouping_"+i).val('value')sets the value of a form.
$("#new_grouping_"+i).text('value')sets the text of an html element.
$("#new_grouping_"+i).html('value')sets the html of an html element.

$("#new_grouping_"+i).val('value')设置表单的值。
$("#new_grouping_"+i).text('value')设置 html 元素的文本。
$("#new_grouping_"+i).html('value')设置 html 元素的 html。

$("#new_grouping_"+i).append('value')prepends something at the beginning of an element $("#new_grouping_"+i).append('value')appends something at end of an element

$("#new_grouping_"+i).append('value')在元素的开头 $("#new_grouping_"+i).append('value')添加一些内容 在元素的结尾添加一些内容

$("#new_grouping_"+i).before('value')places something before an element $("#new_grouping_"+i).after('value')places something after an element.

$("#new_grouping_"+i).before('value')在元素之前放置一些东西 在元素之后 $("#new_grouping_"+i).after('value')放置一些东西。

See More: jQuery Manipulation

查看更多:jQuery 操作

回答by Pergin Sheni

# is important for selector. Here I am setting value to span.

# 对选择器很重要。在这里,我将值设置为跨度。

var i="spanId";
$("#"+ i).html("hello").show();