JavaScript无法用新文本替换文本

JavaScript not able to replace text with new text

本文关键字:文本替换 文本 JavaScript      更新时间:2024-02-22

我正试图在AngularJs和jQuery的帮助下转换所选文本的字体。这是我的密码。一切都很好,但我无法用新文本更改文本。

这是我的代码:

   var app = angular.module('myApp', []);
   app.controller('editor', function($scope) {
     $scope.color = "black";
     $scope.selectedText = "";
     $scope.changeFont = function() {
       if ($scope.selectedText != "") {
         var changedText = "<span style='font-size:" + $scope.kys_selected_font + "px' >" + $scope.selectedText + "</span>";
         alert($scope.selectedText + $scope.kys_selected_font + "      " + changedText);
         document.getElementById("#content").innerHTML.replace($scope.selectedText, changedText);
       } else {
         $("#content").append("<span  id='one' style='font-size:" + $scope.kys_selected_font + "px' > this is some text </span>");
         $("#one").focus();
       }
     };
     $("#content").mouseup(function() {
       $scope.selectedText = window.getSelection();
     });
   });

innerHTML.replace(...)返回一个新字符串,而不是修改现有字符串,因此替换项不会修改元素。

您需要实际更新属性:

var el = document.getElementById("content");
el.innerHTML = el.innerHTML.replace($scope.selectedText, changedText);

(另请注意,根据@IvanSivak的评论,#已从元素ID中删除)