开发者

JQuery: NOT using document.ready and inserting HTML Tags = is this allowed?

开发者 https://www.devze.com 2022-12-23 12:37 出处:网络
is this a valid JQuery usage pattern to : <script type=\"text/javascript\"> $(\"body\").prepend(\'<input type=\"hidden\" id=\"error\" value=\"show\">\');

is this a valid JQuery usage pattern to :

<script type="text/javascript">
        $("body").prepend('<input type="hidden" id="error" value="show">');         
    </script>

That is using Jquery to manipulate / insert HTML Tags when the Document has NOT YET been loaded (by not using document.ready for the inserting into the DOM)?

(Normally I only use document.ready, but in this case I need to insert some Information into the DOM that then is present, when document.ready is called. This is some kind of "happens-before" relations ship I want to achieve so that I am shure when document.ready is called the inserted Form field is available in the document, as I depend on that information.

Tha开发者_JAVA技巧nk you very much jens


Yes, you can do that, but:

  • You have to place the script somewhere after the closing tag of the element that you add elements to. That means that the body element is not a good candidate to prepend anything to.

  • Make sure that the HTML code is valid. If you are using XHTML you should self close the input element.

Consider using the object creation model instead of innerHTML model:

$("#someElement").prepend(
  $('<input/>').attr({ 'type': 'hidden', 'id': 'error' 'value': 'show' })
);

This will create the element as a DOM object instead of using innerHTML to parse the HTML code.


You can but it won't consistently work, as Andrew Bezzub says IE will be the problem (surprise, surprise)

Hard to tell the master plan but for your example could you just not just put this immediately after the <body> opening tag:

document.write('<input type="hidden" id="error" value="show">');


IE may fail loading such HTML - it has problems when someone modifies not fully rendered elements. I think the right choice would be placing such code just after tag.

0

精彩评论

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