jQuery将元素中的html/text替换为元素中的其他元素

jQuery replace html/text of an element with others elements inside

本文关键字:元素 替换 其他 text html jQuery      更新时间:2023-09-26

那么,我有下面的td元素,里面有很多其他的元素:

<td height="43" style="border-bottom:2px solid #2b2b2b;" id="arrow2" >  
<label for="pontoart">Ponto de Articula&ccedil;&atilde;o:</label>
<input type="text" name="pontoart" id="pontoart" value="" required>
<a href="#" id="openbox2" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('+2','','botao de + com hover 2.png',1)">
<img src="botao de + 2.png" alt="" width="24" height="31" id="+2">
</a>
</td>

我有下面的jquery函数。基本上,当单击"+"图像时,它会显示一个隐藏框。我希望它也改变文本显示一个小的html箭头(代码&#10092;),当框是可见的。

$(document).ready(function(){
    $('#openbox2').click(function(){
        $('#box2').toggle();
        if ($('#box2').is(':visible')) {   
            ?
        }
    });
});

我想在if里面放一个.text("&#10092;")。问题是,我很困惑要在选择器中放什么。我希望html代码保持不变,只有❬最后。我已经尝试了所有的id,没有一个给出结果。

<td height="43" style="border-bottom:2px solid #2b2b2b;" id="arrow2" >  
    <label for="pontoart">Ponto de Articula&ccedil;&atilde;o:</label>
    <input type="text" name="pontoart" id="pontoart" value="" required>
    <a href="#" id="openbox2" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('+2','','botao de + com hover 2.png',1)">
    <img src="botao de + 2.png" alt="" width="24" height="31" id="+2">
    </a>&#10092;
    </td> 

有什么想法吗?非常感谢!

您可以使用:

$("#arrow2").append("&#10092;");

这将在td的末尾添加箭头。

如果你想在插入箭头后删除它,你可以为元素创建一个新的jQuery对象,其中包含html实体,而不是仅仅将html实体插入文档而无法删除它。

  • 使用$(this).parent().append(element)将我们的新元素附加到被单击元素的父元素,在本例中是<td>元素。

  • 使用jQuery.remove(element)删除我们的新元素,而不是完全删除它。这意味着我们可以再次创建它,而无需创建一个新的jQuery对象。

var arrow = $('<span>&#10092;</span>');
$(document).ready(function() {
  $('#openbox2').click(function() {
    $('#box2').toggle();
    if ($('#box2').is(':visible')) {
      $(this).parent().append(arrow);
    } else {
      arrow.remove();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td height="43" style="border-bottom:2px solid #2b2b2b;" id="arrow2">
      <label for="pontoart">Ponto de Articula&ccedil;&atilde;o:</label>
      <input type="text" name="pontoart" id="pontoart" value="" required>
      <a href="#" id="openbox2" style="text-decoration: none;">
        <img src="//placehold.it/24x31" alt="" width="24" height="31" id="+2">
      </a>
    </td>
  </tr>
</table>
<div id="box2" style="display:none">Hello foo bar world!</div>

试试这个

$(document).ready(function(){
    $('#openbox2').click(function(){
        $('#box2').toggle();
        if ($('#box2').is(':visible')) {   
           $(this).closest('td').find('label').append('&#10092;')
        } else {
           $(this).closest('td').find('label')...
        }
    });
});

你可以使用jQuery的after方法来放置❬在a标签之后。

$('#openbox2').after('&#10092;');