开发者

is there a way to write the actual DOM to a string

I have an html document

<html>
<head></head>
<body>
<form>
<input type="text" value="" />
</form>
<input type="button" id="doit" value="do it"/>
    <!-- jQuery -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
        </script>            
        <script type="text/javascript">
        $(document).ready(function() {
            $("#doit").click(function(){
            var dom = document.documentElement.innerHTML;
            alert(dom);
            });
        });
        </script>
</body>
</html>

if I edit the text field its value is s开发者_运维问答till the original blank value in the alert...WHY? and how do I see the actual DOM in a string?


You'd need to set each attribute explicitly with the current value: http://jsfiddle.net/GW8eU/.

$("#doit").click(function(){
    $('*').each(function() {
        var $this = $(this);
        for(var i = 0; i < this.attributes.length; i++) {
            try {
                var t = this.attributes[i];
                $this.attr(t.name, $this.prop(t.name));
            } catch(e) {}
        };
    });
    var dom = document.documentElement.innerHTML;
    alert(dom);
});

It's rather dirty and I do not see a real rationale behind outputting the DOM to a string, but it seems to answer your question.

One of the reasons it's dirty is that the try block is essential, because otherwise you'd be setting the type attribute of an input which is immutable. I'm pretty certain this won't work with other special attributes either, but for the value of an input it works fine.

Therefore I would still like to know what's the reason behind wanting the DOM as a string; probably there is a more elegant solution.


I don't know why you want to do this, the only reason I can think of is some kind of WYSIWYG editor that a user interacts with and then can get the HTML source from that? If that is the case then I don't think you are going to be able to achieve this.

If all you need is to get the value of the input field then rather than getting the whole pages HTML, you can get the value of the input by giving your input an ID:

<input type="text" value="" id="input_field" />

and using:

var value = document.getElementById("input_field").value;

Or in jQuery:

var value = $("#input_field").val();

Alternatively, if you want to be able to view the DOM as it is changed by javascript then I recommend Firebug for Firefox, Developer Tools for Chrome/Safari or the Developer Toolbar for IE. These will let you view the DOM as it is held in the browsers memory after modifications by javascript or the user.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜