jQuery可以这样选择dom?

维护之前的代码,看到这一段很费解

let bd = $('body');
let navigationBar = $('<div id="navigationBar-div"></div>');//导航栏
let fileImporter = $('<input type="file" id="file-input" accept="text/plain;" onchange="importVI()">');//脚本导入(不可见)
let importBtn = $('<input type="button" class="navigationBar-btn" value="导入">');//脚本导入按钮
let exportBtn = $('<input type="button" class="navigationBar-btn" value="导出" onclick="exportVI()">');//脚本导出按钮
let resetBtn = $('<input type="button" class="navigationBar-btn" value="重置" onclick="init()">');//重置按钮
let mainContainer = $('<div id="container-div" class="rowFlex-div"></div>');//
阅读 3.2k
4 个回答

有这种用法啊,可以看看文档,就是直接写html字符串进去,生成jQ包装好的离线dom对象,好处是你可以做些稍微复杂点的操作,因为这个dom对象是“离线”的,所以比操作页面上其它“在线”的dom对象性能要略好些,操作完了再appendTo到页面上就行了。

可以这样获取啊,jQuery选择器,最后返回的都是jQueryObject,而非dom。

第一个是Jquery selecter,其他的都是通过html解析生成Jquery对象(可以插入页面和绑定事件)

截取的一段Jquery源码,jquery.fn.init

init = jQuery.fn.init = function( selector, context, root ) {
        ...
        // 如果是<开头>结尾,且length>=3,当成html处理
        if ( typeof selector === "string" ) {
            if ( selector[ 0 ] === "<" &&
                selector[ selector.length - 1 ] === ">" &&
                selector.length >= 3 ) {

                // Assume that strings that start and end with <> are HTML and skip the regex check
                match = [ null, selector, null ];

            } else {
                match = rquickExpr.exec( selector );
            }

            // Match html or make sure no context is specified for #id
            if ( match && ( match[ 1 ] || !context ) ) {

                // HANDLE: $(html) -> $(array)
                if ( match[ 1 ] ) {
                    context = context instanceof jQuery ? context[ 0 ] : context;

                    // Option to run scripts is true for back-compat
                    // Intentionally let the error be thrown if parseHTML is not present
                    jQuery.merge( this, jQuery.parseHTML(
                        match[ 1 ],
                        context && context.nodeType ? context.ownerDocument || context : document,
                        true
                    ) );
    ...
jquery对象转换成dom对象 用[index] 比如 var a=$b[0]
dom对象转换为jquery对象 用$(" ")  比如 var $a=$("#b")

所以你这里这种情况是完全可以的,可以拿到input输入框一起操作,而不用一个个创建,方便了很多。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题