【问题标题】:How to add a tag with classes in a change function如何在更改功能中添加带有类的标签
【发布时间】:2021-08-18 02:04:41
【问题描述】:

按钮

<button id="add-new" type="button" class="btn btn-sm btn-success" data-toggle="modal" data-target="#targetModal"><i class="fas fa-plus-square"></i> Add New CRR Exclusion</button><br><br>

JQuery:

<script>
    $('#action').on('change',function(){
    var buttonText = $(this).find(':selected').data('buttontext');
    $('#add-new').text(buttonText);
    });  
</script>

我有一个更改按钮文本的函数,但是当&lt;script&gt; 触发时我的&lt;i&gt; 标记消失了,我如何在我的函数中添加我的&lt;i&gt; 标记和它的类?

我特别需要这个来保留触发&lt;i class="fas fa-plus-square"&gt;&lt;/i&gt;的功能

默认外观,图标仍然存在(绿色按钮):

当脚本触发时,&lt;i&gt; 消失了:

【问题讨论】:

  • 你能举个例子吗?以 Jsfiddle 为例。我们需要查看更多代码。您是否在控制台中遇到错误
  • 控制台没有错误,我只需要某些代码来适应我的脚本来添加标签及其类

标签: jquery function button


【解决方案1】:

更改您的.lastChild.nodeValue,而不是整个文本。

例子:

$( "#action" ).on("change",function() {
  var buttonText = $(this).find(':selected').data('buttontext');
  $('#add-new').get(0).lastChild.nodeValue = buttonText ;
});

示例片段:

$("#action").on("click", function() {
  var buttonText = "  Your New Text  ";
  $('#add-new').get(0).lastChild.nodeValue = buttonText;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='add-new'>
  <i>Your Icon</i> [ old text ]
</div>

<button id='action'> Change text without losing icon tag </button>

注意:如果您的插件/FrameWork 更改了您的 DOM,您需要检查并捕获适当的元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-09
    相关资源
    最近更新 更多