Javascript 更新HTML值,但忽略当前HTML中的类

Javascript 更新HTML值,但忽略当前HTML中的类,javascript,jquery,html,Javascript,Jquery,Html,我想通过Jquery更新元素中的HTML。但是有一个班级我不想被感动。这里有一个例子。我想更新hello文本,但我想保持.arrow类的灵活性。有没有一种不必在jquery中添加.arrow html的方法 我的笔: HTML 我知道我能做到,但感觉很笨拙: $('.contactfield').click(function (event) { $(this).html('test<div class="arrow"><img src="images/arrow.pn

我想通过Jquery更新元素中的HTML。但是有一个班级我不想被感动。这里有一个例子。我想更新hello文本,但我想保持.arrow类的灵活性。有没有一种不必在jquery中添加.arrow html的方法

我的笔:

HTML

我知道我能做到,但感觉很笨拙:

 $('.contactfield').click(function (event) {
    $(this).html('test<div class="arrow"><img src="images/arrow.png" /></div>'); 
});
$('.contactfield')。单击(函数(事件){
$(this.html('test');
});

在这种情况下,您不需要在“.contactfield”中更新整个html

请使用以下命令:

<div class="contactfield"><span class="dynamic">hello</span>
   <div class="arrow">
     <img src="images/arrow.png" />
   </div>
 </div>

$('.contactfield').click(function (event) {
    $(this).find('.dynamic').html('test'); 
});
你好 $('.contactfield')。单击(函数(事件){ $(this.find('.dynamic').html('test'); });
在这种情况下,您不需要在“.contactfield”中更新整个html

请使用以下命令:

<div class="contactfield"><span class="dynamic">hello</span>
   <div class="arrow">
     <img src="images/arrow.png" />
   </div>
 </div>

$('.contactfield').click(function (event) {
    $(this).find('.dynamic').html('test'); 
});
你好 $('.contactfield')。单击(函数(事件){ $(this.find('.dynamic').html('test'); });
您可以克隆它;这样,您就不必在
hello

jQuery

$('.contactfield').on('click', function(e){
  var arrow = $('.arrow').clone().wrap('<div>').parent().html();
  $(this).html('test' + arrow);
});
jQuery
$('contactfield')。在('click',函数(e)上{
var arrow=$('.arrow').clone().wrap(''.parent().html();
$(this.html('test'+箭头);
});

您可以克隆它;这样,您就不必在
hello

jQuery

$('.contactfield').on('click', function(e){
  var arrow = $('.arrow').clone().wrap('<div>').parent().html();
  $(this).html('test' + arrow);
});
jQuery
$('contactfield')。在('click',函数(e)上{
var arrow=$('.arrow').clone().wrap(''.parent().html();
$(this.html('test'+箭头);
});

如果您只想更改文本,您可以访问包装文本的。否则,如果您可以更改标记,请按照其他人的建议操作,并将文本包装在
或其他标记中

$('.contactfield').click(function (event) {
  $(this)
    .contents()
    .filter((i,node) => node.nodeType === Node.TEXT_NODE)[0]
    .nodeValue = "test"
});

如果您只想更改文本,则可以访问包装文本的。否则,如果您可以更改标记,请按照其他人的建议操作,并将文本包装在
或其他标记中

$('.contactfield').click(function (event) {
  $(this)
    .contents()
    .filter((i,node) => node.nodeType === Node.TEXT_NODE)[0]
    .nodeValue = "test"
});
将表示“hello”的文本放在它自己的元素中,如a,并给该元素一个类。这样,您就可以只针对文本,而不影响其他任何内容。另外,您可以使用.text而不是.html来更改文本。将表示“hello”的文本放在它自己的元素中,如a,并给该元素一个类。这样,您就可以只针对文本,而不影响其他任何内容。此外,您可以使用.text而不是.html来更改文本。