How to append/prepend/create a text node with jQuery

前端 未结 3 1507
天命终不由人
天命终不由人 2020-12-11 00:03

Possible Duplicate:
Escaping text with jQuery append?

My HTML is somewhat like this:

相关标签:
3条回答
  • 2020-12-11 00:22

    The createTextNode approach is probably the best way to go. If you want to have a jQuery-ish syntax, you could make a plugin.

    $.fn.appendText = function(text) {
        return this.each(function() {
            var textNode = document.createTextNode(text);
            $(this).append(textNode);
        });
    };
    
    0 讨论(0)
  • 2020-12-11 00:26

    $.text() accepts also a function as parameter. This function will receive an index and the current text. The return value of the function will be set as the new text.

    .text( function )

    function
    Type: Function( Integer index, String text ) => String
    A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments.

    $("li").text(function(idx, txt) {
       return txt + " <item>";
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>

    0 讨论(0)
  • 2020-12-11 00:36

    You can use;

    $.extend({
            urlEncode: function(value) {
                var encodedValue = encodeURIComponent(value);
                encodedValue = encodedValue.replace("+", "%2B");
                encodedValue = encodedValue.replace("/", "%2F");
    
                return encodedValue;
            },
            urlDecode: function(value) {
                var decodedValue = decodeURIComponent(value);
                decodedValue = decodedValue.replace("%2B", "+");
                decodedValue = decodedValue.replace("%2F", "/");
    
                return decodedValue;
            }
    });
    

    to escape HTML characters before you append to the DOM.

    Use it like; $.urlEncode(value)

    Using it; $('#selector').append($.urlEncode(text));

    Update #1

    You could this $('#selector').html($('#selector').html() + text);

    I suspected this was what you wanted.

    0 讨论(0)
提交回复
热议问题