javascript - 为什么我无法在 v3 中将普通变量转换为 jQuery 对象?

标签 javascript jquery

我们刚刚将 jQuery 版本从 v1.7 升级到 v3.4.1。我们有代码将 jQuery 对象(DOM 中还不存在,我猜这是这个问题的根本原因)传递给函数。但是,当尝试处理这个新创建的变量时,它仅返回根 jQuery 函数本身:jQuery.fn.init {}

这个答案帮助我意识到了这个问题:Help understanding jQuery's jQuery.fn.init Why is init in fn

实际片段:

create: function (params) {
        console.log('params.target:', params.target);
        var $target, id;

        if (_.isString(params.target)) {
            if (params.target.charAt(0) === '#') {
                $target = $('#send-to-friend-dialog');
                console.log('$target1: ', $target);
            } else {
                $target = $('#' + params.target);
            }
        } else if (params.target instanceof jQuery) {
            $target = params.target;
        } else {
            $target = $('#dialog-container');
        }

        console.log('$target.length: ', $target.length)

        // if no element found, create one
        if ($target.length === 0) {
            console.log('$target2 : ', $target);
            if ($target.selector && $target.selector.charAt(0) === '#') {
                id = $target.selector.substr(1);
                $target = $('<div>').attr('id', id).addClass('dialog-content').appendTo('body');
            }
        }

        // create the dialog
        console.log('$target3: ', $target);
        this.$container = $target;
        this.$container.dialog($.extend(true, {}, this.settings, params.options || {}));
        return this.$container;
    },

v1.12.4 中的输出: /image/DkPtx.png

v3.4.1 中的输出: /image/2PgWR.png

因此,虽然它已定义,但对象本身在两个版本中的输出都非常不同,我想知道为什么?

谢谢!

最佳答案

jQuery .selector 属性在 1.7 中已弃用,并在 3.0 中删除。请参阅https://api.jquery.com/selector/ 。这是一个内部接口(interface),不适合由应用程序使用。

您需要重新设计代码,这样就不需要这个了。该文档提出了一种替代方案:

For example, a "foo" plugin could be written as $.fn.foo = function( selector, options ) { /* plugin code goes here */ };, and the person using the plugin would write $( "div.bar" ).foo( "div.bar", {dog: "bark"} ); with the "div.bar" selector repeated as the first argument of .foo().

关于javascript - 为什么我无法在 v3 中将普通变量转换为 jQuery 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57084856/

相关文章:

javascript - React.js 引用没有出现在对象内部

javascript - 单击图像以更改网站上的文本和另一图像

php - $.ajax 问题 - 未捕获的 TypeError : Illegal invocation

javascript - 如何在现有选项卡中引入内容

javascript - 提交表单后 Bootstrap 模式不关闭

javascript - AngularJs 将模型值+模型名称传递给 Controller ​​中的函数

javascript - 每行的折叠按钮

c# - 使用 Jquery 从文本框向列表框添加项目

javascript - 使用 2 种情况查找某些变量的正确方法

javascript - 设置选中的菜单项类 ="selected"服务器端还是使用 JavaScript 更专业?