[英]JQuery replace html element contents if ID begins with prefix
我希望移动或复制HTML元素的内容。 之前已经问到这个问题,我可以使用innerHTML()或Jquery的html()方法来工作,但我正在尝试自动化它。
如果元素的ID以'rep_'开头,则在下划线后面替换元素的内容。
所以,
<div id="rep_target">
Hello World.
</div>
将取代:
<div id="target">
Hrm it doesn't seem to work..
</div>
我试过了:
$(document).ready(function() {
$('[id^="rep_"]').html(function() {
$(this).replaceAll($(this).replace('rep_', ''));
});
});
-和-
$(document).ready(function() {
$('[id^="rep_"]').each(function() {
$(this).replace('rep_', '').html($(this));
});
});
似乎没有工作,但是,这确实有效,只有手动:
var target = document.getElementById('rep_target').innerHTML;
document.getElementById('target').innerHTML = target;
相关,但这只是文字。 JQuery替换id中包含字符串的元素的所有文本
第一部分有两个基本选项:用HTML字符串替换,或用实际元素替换。
选项#1:HTML
$('#target').html($('#rep_target').html());
选项#2:元素
$('#target').empty().append($('#rep_target').children());
如果你没有偏好,后一个选项更好,因为浏览器不必重新构造所有DOM位(每当浏览器将HTML转换为元素时,它就需要工作,从而影响性能;选项#2避免了这一点通过不使浏览器创建任何新元素来工作。
这应该涵盖更换内部。 您还想更改元素的ID,这只有一种方式(我知道)
var $this = $(this)
$this.attr($this.attr('id').replace('rep_', ''));
所以,把它们放在一起,比如:
$('[id^="rep_"]').each(function() {
var $this = $(this)
// Get the ID without the "rep_" part
var nonRepId = $this.attr('id').replace('rep_', '');
// Clear the nonRep element, then add all of the rep element's children to it
$('#' + nonRepId).empty().append($this.children());
// Alternatively you could also do:
// $('#' + nonRepId).html($this.html());
// Change the ID
$this.attr(nonRepId);
// If you're done with with the repId element, you may want to delete it:
// $this.remove();
});
应该做的伎俩。 希望有所帮助。
使用attr
方法获取id,删除前缀,从中创建选择器,从元素中获取HTML代码,并从函数返回:
$('[id^="rep_"]').html(function() {
var id = $(this).attr('id');
id = id.replace('rep_', '');
var selector = '#' + id;
return $(selector).html();
});
或者干脆:
$('[id^="rep_"]').html(function() {
return $('#' + $(this).attr('id').replace('rep_', '')).html();
});
根据我的问题,我的理解是你想通过删除重新_前缀来替换id,然后更改该div的内容。 这个脚本会这样做。
$(document).ready(function() {
var items= $('[id^="rep_"]');
$.each(items,function(){
var item=$(this);
var currentid=item.attr("id");
var newId= currentid.substring(4,currentid.length);
item.attr("id",newId).html("This does not work");
alert("newid : "+newId);
});
});
工作样本: http : //jsfiddle.net/eh3RL/13/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.