jQuery:选择和操作 DOM 之外的 html 元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11813691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:58:33  来源:igfitidea点击:

jQuery: Selecting and manipulating html elements outside the DOM

jqueryhtmldomjquery-selectors

提问by Ben Pearce

As far as I can tell only objects that have been loaded into the DOM can be manipulated with selectors. This is illustrated in the example below, when the button is clicked it's click handler un-successfully tries to select an element in the page to be loaded and change it's html before. I surmise that because the click handler is triggered before the link page is loaded into the DOM the selector doesn't effect the element.

据我所知,只有已加载到 DOM 中的对象才能使用选择器进行操作。这在下面的示例中说明,当单击按钮时,它的单击处理程序未成功尝试选择页面中要加载的元素并更改它之前的 html。我推测因为在链接页面加载到 DOM 之前触发了点击处理程序,所以选择器不会影响元素。

My question is, is there any way to instantiate an external chunk of html and manipulate it before inserting it into the DOM.

我的问题是,有没有办法在将外部 html 块插入到 DOM 之前对其进行实例化并对其进行操作。

script_1.js:

脚本_1.js:

$(document).ready(function () {
    $("#testButton").click(function () {
        $("#externalPageDiv").html("hello world");
    });
});

External Page html:

外部页面 html:

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0-rc.1/jquery.mobile-1.1.0-rc.1.min.css"
    />
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.1.0-rc.1/jquery.mobile-1.1.0-rc.1.min.js"></script>
    <script src="script_1.js"></script>
</head>

<body>
    <div data-role="page" id="externalPage" data-add-back-btn="true">
        <div data-role="content" id="externalPageContent">
            <div id="externalPageDiv"></div>external page</div>
    </div>
</body>

Main Page Html:

主页 Html:

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0-rc.1/jquery.mobile-1.1.0-rc.1.min.css"
    />
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.1.0-rc.1/jquery.mobile-1.1.0-rc.1.min.js"></script>
    <script src="script_1.js"></script>
</head>

<body>
    <div data-role="page" id="internalPage_1" data-add-back-btn="true">
        <div data-role="content" id="internalPageContent_1">
            <a href="externalPage.html" id="testButton" data-role="button" rel="external">Page Change</a>
        </div>
    </div>
    <div data-role="page" id="mainPage" data-add-back-btn="true">
        <div data-role="content" id="mainPageContent">Main Page</div>
    </div>
</body>

回答by davidbuzatto

I'm correcting my incorrect comment. Yes, you can do something like this, but reading the jQuery documentation, it is said that the code is inserted in the DOM http://api.jquery.com/jQuery/#jQuery2. So, even the code below seems to not insert nothing in the DOM, it is indeed inserted.

我正在纠正我的错误评论。是的,你可以做这样的事情,但阅读 jQuery 文档,据说代码被插入到 DOM http://api.jquery.com/jQuery/#jQuery2 中。所以,即使下面的代码似乎没有在 DOM 中插入任何内容,它确实是插入了。

Try this:

尝试这个:

var codeToProcess = "<div>" +
                    "    <div id='myDiv1'>a</div>" +
                    "    <div id='myDiv2'>b</div>" +
                    "    <div id='myDiv3'>c</div>" +
                    "</div>";

var $toProcess = $( codeToProcess );
$toProcess.find( "div" ).addClass( "processed" );

// getting by id before insertion
alert( $toProcess.find( "#myDiv1" ).html() );
alert( $( "#myDiv1" ).html() ); // this will return null, since the divs
                                // were not yet added to the document

$toProcess.appendTo( "#container" );
// or $( "#container" ).html( $toProcess );

// getting by id after insertion
alert( $( "#myDiv2" ).html() );

jsFiddle: http://jsfiddle.net/davidbuzatto/me7T3/

jsFiddle:http: //jsfiddle.net/davidbuzatto/me7T3/

Edit:

编辑:

To insert code from a external file, you can use the load function. You can see an example here: http://jsfiddle.net/davidbuzatto/zuFsc/Note that in this example I used the echo service os jsFiddle to emulate a external file. Take a look here How do you output a view file as an ajax response in Java?and here http://api.jquery.com/load/

要从外部文件插入代码,您可以使用加载函数。您可以在此处查看示例:http: //jsfiddle.net/davidbuzatto/zuFsc/请注意,在此示例中,我使用了 echo 服务 os jsFiddle 来模拟外部文件。看这里How do you output a view file as an ajax response in Java?在这里http://api.jquery.com/load/

回答by jfriend00

You can use javascript to manually create DOM elements that are not inserted into the DOM hierarchy and you can manipulate them as much as you want before inserting them into the DOM.

您可以使用 javascript 手动创建未插入到 DOM 层次结构中的 DOM 元素,并且可以在将它们插入到 DOM 之前随意操作它们。

But, if you're trying to manipulate DOM elements that are created by your page HTML before that page HTML has been parsed, you cannot do that. The DOM elements don't exist at that point so there's nothing to manipulate unless you manually created them as described in the first paragraph.

但是,如果您尝试操作在页面 HTML 被解析之前由页面 HTML 创建的 DOM 元素,则不能这样做。那时 DOM 元素不存在,因此除非您按照第一段中的描述手动创建它们,否则没有什么可操作的。

Some operations only work on DOM elements inserted into the DOM hieararchy such as document.getElementById(), but other methods can be used on a piece of DOM that isn't in the main hierarchy such as item.getElementsByClassName()where itemis a DOM element not in the DOM hierarchy.

某些操作仅适用于插入到 DOMdocument.getElementById()层次结构item.getElementsByClassName()item的 DOM 元素,例如,但其他方法可用于不在主层次结构中的一块 DOM,例如DOM 元素不在 DOM 层次结构中的位置。

In jQuery, the default context is the document so a simple selector operation like $(".foo")will only search DOM elements in the DOM document hierarchy. But, if you pass a specific context, $(".foo", item), then the jQuery selector will search that context, not the main document.

在 jQuery 中,默认上下文是文档,因此一个简单的选择器操作,例如$(".foo")只会在 DOM 文档层次结构中搜索 DOM 元素。但是,如果您传递特定的上下文, $(".foo", item),则 jQuery 选择器将搜索该上下文,而不是主文档。