javascript - jQuery:如何用文本区域 $ ('#myId' ).attr ('value' ) 中的另一个文本替换某些文本?

标签 javascript jquery html

如何用 $('#myId').attr('value') 中的另一个文本替换某些文本文本区域?

我尝试过这样的事情:

$(function() {
    var selection;
    var replaceStr;

    var prependStr = "";
    var appendStr = "";

    var temp = "";

    $('input[type="button"]').click(function() {
        if($(this).attr('id') == 'underline')
        {
            prependStr = "<span style = 'text-decoration: underline;'>";
            appendStr = "</span>";
        }
        else if($(this).attr('id') == 'italic')
        {
            prependStr = "<span style = 'font-style: italic;'>";
            appendStr = "</span>";
        }
        else if($(this).attr('id') == 'bold')
        {
            prependStr = "<span style = 'font-weight: bold;'>";
            appendStr = "</span>";
        }
        else if($(this).attr('id') == 'center')
        {
            prependStr = "<span style = 'text-align: center;'>";
            appendStr = "</span>";
        }
        else if($(this).attr('id') == 'link')
        {
            prependStr = "<a href = ''>";
            appendStr = "</a>";
        }
        else if($(this).attr('id') == 'img')
        {
            prependStr = "<img src = '";
            appendStr = "' />";
        }
        else if($(this).attr('id') == 'h1')
        {
            prependStr = "<h1>";
            appendStr = "</h1>";
        }
        else if($(this).attr('id') == 'h2')
        {
            prependStr = "<h2>";
            appendStr = "</h2>";
        }
        else if($(this).attr('id') == 'h3')
        {
            prependStr = "<h3>";
            appendStr = "</h3>";
        }

        $('#page').focus();
        selection = window.getSelection();

        if(selection != '')
        {
            replaceStr = prependStr+selection+appendStr;

            temp = $('#page').attr('value');
            temp.replace(selection, replaceStr);//Not working

            $('#page').attr('value', temp);
        }
    });

});

除了函数 .replace() 之外,整个代码都可以工作。我用谷歌搜索了很多东西,但没有找到在 $('#page').attr('value') 上执行此操作的函数。

最佳答案

看看this link .

temp.replace(selection, ReplaceStr) 不会更改变量“temp”。它返回一个新字符串。

像这样做某事: temp = temp.replace(选择,replaceStr); $('#page').attr('value', temp);

关于javascript - jQuery:如何用文本区域 $ ('#myId' ).attr ('value' ) 中的另一个文本替换某些文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34793735/

相关文章:

JavaScript -Change CSS color for 5 seconds - 如何添加缓动效果?

javascript - Active X 控件 JavaScript

jquery - 链接在加载后保持粗体

javascript - 消除 Internet Explorer 中 Thread.Sleep 上的死锁?

c# - 如何在angularjs中使用ng-repeat渲染mathml?

jquery - 滚动时图像不透明度发生变化

javascript - 如何将 WordPress jQuery 库添加到前端

javascript - 如何阻止 keydown 事件被卡住?

javascript - 带有 Ajax 调用的 Bootstrap Popover 不显示数据

jqueryUI datepicker - altfield 隐藏?