如果我添加 Font Awesome ,功能更改文本不起作用

标签 function font-awesome innerhtml getelementbyid

这是我的函数,它从我的按钮中获取 id 并更改文本:

var modal_button_update = document.getElementById("modal_button_text");
if (modal_button_update.innerHTML === "Add") { modal_button_update.innerHTML = "Update"; } 
使用此按钮可以正常工作(添加变为更新)
<button type="button" class="btn btn-primary save_button add_group" id="modal_button_text">Add</button>
但是由于某种原因,如果我尝试添加一个 Font Awesome 图标,它就不会再改变了:
<button type="button" class="btn btn-primary save_button add_group" id="modal_button_text"><i class="fas fa-save" aria-hidden="true"></i>Add</button>
可能是什么原因?

最佳答案

我运行了你的代码。似乎问题在于您正在检查您的 modal_button_update 是否按钮的innerHTML 等于Add。原始按钮:

<button type="button" class="btn btn-primary save_button add_group" id="modal_button_text">Add</button>
之所以有效,是因为您的 modal_button_update 的 innerHTML正是“添加”,但您修改了 modal_button_update :<button type="button" class="btn btn-primary save_button add_group" id="modal_button_text"><i class="fas fa-save" aria-hidden="true"></i>Add</button>不起作用,因为innerHTML 是<i class="fas fa-save" aria-hidden="true"></i>&gt;Add这不等于 (===) 到“添加”。
我选择了三种不同的方式来解决这个问题:
  • 删除 <i class="fas fa-save" aria-hidden="true">元素并将字体很棒的图标放在按钮类中,例如:<button type="button" class="btn btn-primary save_button add_group fas fa-save" id="modal_button_text">Add</button>`
  • 将您的 Javascript 更改为:var modal_button_update = document.getElementById("modal_button_text"); if (modal_button_update.innerHTML.includes("Add")) { modal_button_update.innerHTML = "Update"; }此处按钮检查innerHTML 是否包含“添加”。
  • 保持 Font Awesome 图标 :
    在上面的两个解决方案中,当成功将 innerHTML 更改为“更新”时,您的 Javascript 代码将删除 font-awesome 类的按钮元素。 imo,它更易于使用 jQuery改变按钮的值来解决这个问题,如:

  • ---HTML---
                        <button type="button" class="btn btn-primary save_button add_group" id="modal_button_text"><i class="fas fa-save" aria-hidden="true"></i>Add</button>
    
    ---Javascript--
    if ($('#modal_button_text').html().includes("Add")) {
        $('#modal_button_text').html("Update");
    }
    

    关于如果我添加 Font Awesome ,功能更改文本不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69938812/

    相关文章:

    c++ - 本地声明的外部函数

    javascript - "this"函数上下文中的 javascript 关键字

    R在控制台中显示两个堆叠的进度条(带代码)

    javascript - 通过 POST 调用 HTML Javascript 函数

    javascript - Font Awesome 图标未在 Phonegap iOS 应用程序中呈现

    javascript - 我可以在 html5 通知中显示 Font Awesome 图标吗

    java - 使用 AwesomeFont 中的自定义字体和 Java Swing 中的 unicode 字符向 JButton 添加图标?

    javascript - JS输出消息打印在表单的div标签上

    javascript string.lastIndexOf 不适用于 span innerHTML

    javascript innerHTML打印错位