获取onclick源码后,无法使用element的方法

After retrieving the onclick source, can't use methods of element

这是"myPlugin.js"的内容:

(function ($) {
    $.fn.MyPlugin = function (options) {
    // retrieve somespan
    somespan.html("<a href="#" onclick="javascript: SelectLink(this);"></a>");
})(jQuery);

function SelectLink(element) {
    console.log(element);
    if (element.parent("span").parent("li.clickable")) {
        alert("is clickable");
    } else {
        alert("is not clickable");
    }
}

当我单击我们在 div 中创建的 link 元素时,控制台显示:

TypeError: element.parent is not a function
<a onclick="javascript: SelectLink(this);" href="#">

所以它知道我们离开的元素,但我不能用它做任何进一步的事情?为什么会这样?

这里的元素是一个 dom 元素引用而不是一个 jQuery 对象,因此其中没有名为 parent() 的方法。

您可以获得元素的 jQuery 包装器并调用包装器上的方法

function SelectLink(element) {
    console.log(element);
    var $element = $(element);
    if ($element.parent("span").parent("li.clickable")) {
        alert("is clickable");
    } else {
        alert("is not clickable");
    }
}

由于您正在开发插件,因此不要使用内联事件处理程序,而是使用 jQuery 事件处理程序,例如

(function ($) {
    $.fn.MyPlugin = function (options) {

        var $a = $('<a href="#"></a>');
        somespan.html($a);
        $a.click(SelectLink)
    }

    function SelectLink(event) {
        var $this = $(this);
        //if ($this.closest("li.clickable").length) {
        if ($this.parent("span").parent("li.clickable").length) {
            alert("is clickable");
        } else {
            alert("is not clickable");
        }
    }

})(jQuery);