如何使用jQuery获取id元素的一部分? [英] How to get a part of id element using jQuery?
问题描述
如何从带有id =old- [id]的span获取Some text并将其放入id =new- [id]?
< span id =old-1>一些文字< / span>
< span id =new-1>< / span>
< span id =old-5>一些文字< / span>
< span id =new-5>< / span>
我不知道如何获得 id的数字部分
没有 substring()
函数。
我认为存在更正确的解决方案。
谢谢。
由于你的问题并不完全清楚你在问什么,我会给你一个一堆不同的例子:
对于一个id,你可以这样做:
$( #新-1)文本($( #老-1)文本()。)。
如果您要执行此操作的一系列顺序ID,则可以执行以下操作:
for(var i = 1; i< = 5; i ++){
$(#new- + i)。text($(#old-+ i).text());
}
如果是HTML,而不仅仅是文本,你可以使用.html() .text()的位置在上面的代码中。
$(#new-1)。html($( #老-1\" )的html())。
或
for(var i = 1; i< = 5; i ++){
$(#new-+ i).html($(#old-+ i).html( ));
}
如果要查找ID为old-的所有对象并处理所有这些,无论他们有多少和有多少数字,你都可以这样做:
$('[ id ^ =old - ]')。each(function(){
var newid = this.id.replace(/ old /,new);
$(#+ newid ).html($(this).html())
})
这将创建一个jQuery对象,其中所有对象的id都以old-开头,然后将old替换为new以创建目标id值,并使用该值将HTML从源复制到目标。 / p>
如果在名为 elem
的变量中有给定对象,并且您只想提取id的数字部分值,您可以使用常规表达式匹配数字部分,如下所示:
var matches = elem.id.match(/ \d + $ /);
if(matches){
var numString = matches [0];
}
How I can get a "Some text" from span with id="old-[id]" and put it in id="new-[id]" ?
<span id="old-1">Some text</span>
<span id="new-1"></span>
<span id="old-5">Some text</span>
<span id="new-5"></span>
I don't know how to get a digital part of id
without substring()
function.
I think exists is more correct solution.
Thanks.
As your question is not entirely clear what you're asking, I'll offer you a bunch of different examples:
For a single id, you could do this:
$("#new-1").text($("#old-1").text());
If you have a bunch of sequential IDs that you want to do this on, you could do this:
for (var i = 1; i <= 5; i++) {
$("#new-" + i).text($("#old-" + i).text());
}
If it's HTML, not just text, you can use .html() in place of .text() in the above code.
$("#new-1").html($("#old-1").html());
or
for (var i = 1; i <= 5; i++) {
$("#new-" + i).html($("#old-" + i).html());
}
If you want to find all objects that have IDs that start with "old-" and process all of them regardless of how many and what numbers are on them, you could do this:
$('[id^="old-"]').each(function() {
var newid = this.id.replace(/old/, "new");
$("#" + newid).html($(this).html())
})
This will create a jQuery object of all objects that have an id that starts with "old-" and then replace the "old" with "new" to create the destination id value and use that to copy the HTML from the source to the destination.
If you have a given object in a variable named elem
and you want to extract just the numeric portion of the id value, you can use a regular expresssion to match the numeric portion like this:
var matches = elem.id.match(/\d+$/);
if (matches) {
var numString = matches[0];
}
这篇关于如何使用jQuery获取id元素的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!