JQuery change inner text but preserve html

前端 未结 14 2768
名媛妹妹
名媛妹妹 2020-12-01 06:56

I would like to change the text of a HTML element but preserve the rest of the inner html with jQuery.

For instance:

Some         


        
14条回答
  •  悲&欢浪女
    2020-12-01 07:52

    This is an improvement I've made to the jquery.uniform library. Specifically the $.uniform.update() function. I took the idea from acheong87 and changed it a bit.

    The idea is to change the text in a span but preserve the inner HTML and event bindings. No need to store and append HTML this way.

    if ($e.is("input[type=button]")) {
        spanTag = $e.closest("span");
        var contents = spanTag.contents();
    
        if (contents.length) {
            var text = contents.get(0);
    
            // Modern browsers support Node.TEXT_NODE, IE7 only supports 3
            if (text.nodeType == 3)
                text.nodeValue = $e.val();
        }
    }
    

提交回复
热议问题