gpt4 book ai didi

javascript - jquery 和 HTML 放置

转载 作者:行者123 更新时间:2023-11-28 16:03:08 25 4
gpt4 key购买 nike

我正在尝试使用 jQuery UI,特别是对话框。首先我尝试了示例代码,它工作正常:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>dialog demo</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>

</head>
<body>
<button id="opener">open the dialog</button>
<div id="dialog" title="Dialog Title">I'm a dialog</div>
<script>

$( "#dialog" ).dialog({ autoOpen: false });
$( "#opener" ).click(function() {
$( "#dialog" ).dialog( "open" );
});

</script>
</body>
</html>

现在,我尝试在脚本中动态创建按钮和对话框,因此我将代码重写为:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>dialog demo</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>

<script>

// Create button
var open_button = document.createElement("button");
open_button.appendChild(document.createTextNode("Open the dialog"));
open_button.setAttribute("id", "opener");

document.body.appendChild(open_button);


// Creating dialog
var my_dialog = document.createElement("div");
my_dialog.setAttribute("title", "Dialog");
my_dialog.setAttribute("id", "dialog");

document.body.appendChild(my_dialog);

$( "#dialog" ).dialog({ autoOpen: false });
$( "#opener" ).click(function() {
$( "#dialog" ).dialog( "open" );
});
</script>

</head>
<body>
</body>
</html>

现在它失败并出现错误“body is null”。这是为什么?

但即使我在主体内创建虚拟 DOM:

<div id="dummy_div"></div>

...然后,在脚本内部,将按钮和对话框附加到其中而不是正文,但它仍然不起作用。

$("#dummy_div").append(open_button);
$("#dummy_div").append(my_dialog);

我可能缺少一些 HTML 基础知识,如果有任何解释,我将不胜感激。谢谢。

最佳答案

您正尝试在 HTML 呈现之前创建该元素。

使用这个:

 $(function() {
$("#dummy_div").append(open_button);
$("#dummy_div").append(my_dialog);

$( "#dialog" ).dialog({ autoOpen: false });
$( "#opener" ).click(function() {
$( "#dialog" ).dialog( "open" );
});
});

祝你好运

注意

$(function() { ... }); is the same thing as $(document).ready()

Read about document.ready() here

阅读该内容以获取有关 DOM 就绪的更多信息。

关于javascript - jquery 和 HTML 放置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16201033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com