Javascript Removing Whitespace When It Shouldn't?

前端 未结 10 2037
谎友^
谎友^ 2020-12-11 05:29

I have a HTML file that has code similar to the following.


&         
相关标签:
10条回答
  • 2020-12-11 05:53

    Just checked it and it looks like wrapping with the pre tag should do it.

    0 讨论(0)
  • 2020-12-11 05:53

    Just an opinion here and not canonical advice, but you're headed for a world or hurt if you're trying to extract exact text values from the DOM using the inner/outer HTML/TEXT properties via Javascript. Different browsers are going to return slightly different values, based on how the browser "sees" the internal document.

    If you can, I'd change the HTML you're rendering to include a hidden input, something like

    <table>
        <tr>
        <td id="MyCell">Hello  World<input id="MyCell_VALUE" type="hidden" value="Hello  World" /></td>
        </tr>
    </table>
    

    And then grab your value in javascript something like

    document.getElementById(cell2.Element.id+'_VALUE').value
    

    The input tags were designed to hold values, and you'll be less likely to run into fidelity issues.

    Also, it sounds like you're using a .NET control of some kind. It might be worth looking through the documentation (ha) or asking a slightly different question to see if the control offers an official client-side API of some kind.

    0 讨论(0)
  • 2020-12-11 05:54

    Just a tip, innerText only works in Internet Explorer, while innerHTML works in every browser... so, use innerHTML instead of innerText

    0 讨论(0)
  • 2020-12-11 05:57

    Edit: I am wrong, ignore me.

    You can get a text node's nodeValue, which should correctly represent its whitespace.

    Here is a function to recursively get the text within a given element (and it's library-safe, won't fail if you use something that modifies Array.prototype or whatever):

    var textValue = function(element) {
        if(!element.hasOwnProperty('childNodes')) {
            return '';
        }
        var childNodes = element.childNodes, text = '', childNode;
        for(var i in childNodes) {
            if(childNodes.hasOwnProperty(i)) {
                childNode = childNodes[i];
                if(childNode.nodeType == 3) {
                    text += childNode.nodeValue;
                } else {
                    text += textValue(childNode);
                }
            }
        }
        return text;
    };
    
    0 讨论(0)
提交回复
热议问题
Hello World