考虑以下创建 JQuery UI 对话框的代码:
function showBox() {
$('<div />').html('This is my dialog').dialog({
buttons: {
'Okay': function(){
$(this).dialog('close');
},
'Return': function(){
$(this).dialog('close');
}
},
close: function(){ $(this).dialog('destroy').remove(); },
modal: true,
title: 'My Dialog Title',
width: 350
});
}
以及 HTML 页面正文中的一个简单链接:
<a href="#" onClick="showBox()">Click to open a box</a>
该代码可以完美地启动 JQuery UI 对话框。
我的问题是:为什么使用 <div />
作为$()
参数实际上生成了一个工作框?
我一直用<div></div>
作为我的$()
对话框的参数。在 HTML 中,div 是需要开始和结束标记的 block 级元素,那么为什么只使用 <div />
一个有效的选项?
最佳答案
因为就是这样jQuery旨在工作:
In most cases, jQuery creates a new element and sets the innerHTML property of the element to the HTML snippet that was passed in. When the parameter has a single tag (with optional closing tag or quick-closing) —
$( "<img />" )
or$( "<img>" )
,$( "<a></a>" )
or$( "<a>" )
— jQuery creates the element using the native JavaScript createElement() function.
因此,在 jQuery 中创建元素时,所有这些都是等效的:
-
<div></div>
-
<div />
-
<div>
关于javascript - 为什么使用 '<div/>' 作为 JQuery UI 对话框方法中的对象有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20571854/