javascript - 将变量作为 JQuery CSS 选择器传递不起作用

标签 javascript jquery css variables jquery-selectors

这是我的第一部分代码:

$('ul li').click(function(){ //when an <li> is clicked

    $('ul .clicked').removeClass('clicked'); // remove .clicked class from any other <li>'s inside a <ul>
    $(this).addClass('clicked'); // add .clicked class to the clicked <li> ($(this))

    screen = $(this).attr('id'); // screen = the clicked elements' id
    screen = "#" + screen; // screen = the clicked elements' id with a # infront of it 
    $(screen).screenSlide(); // is basically = $('#elementsID').screenSlide();, correct?
});

这很奇怪,因为在我之前写的一个函数中,除了最后一步,我做了完全相同的事情,而不是将 screen 作为选择器传递,我将 screen 插入一个数组,然后我抓取数组 [0](这是#elementsID 没有任何引号)并将其用作选择器并且它起作用了。但是向前看,screenSlide 是

function screenSlide(){ // $(this) should = an <li> who's id is screen
    var test = $(this).attr('class');
    alert(test);
    $(this).addClass('current'); // add the .current class to $(this), which should be an <li>
    $(this).slideDown();
};

现在,警报测试没有发出任何警报,所以我猜测将屏幕作为 CSS 选择器传递是行不通的。可以看到,screenSlide 函数应该是给 $(this)

  • 添加一个类,然后让它向上滑动。

    知道哪里出了问题吗?

  • 最佳答案

    按照您定义的方式,screenSlide 只是一个函数,没有附加到 jquery 对象。为了在 jquery 对象上作为函数调用,您需要将其添加为 $.fn.screenSlide

    $.fn.screenSlide = function(){
        var test =this.attr('class');
        alert(test);
        this.addClass('current'); // add the .current class to $(this), which should be an <li>
        this.slideDown();
        return this; //return this to enable chaining
    }
    

    在这个函数中,您不需要将 jquery 对象重新定义为 $(this),因为 this 已经是一个 jquery 对象,并且还返回 this 以启用它以进行链接。

    如果你想单独调用它,那么你可以使用 function.call

    screenSlide.call($(this));
    

    有了这个 this 又是一个 jquery 对象,你不需要在你的函数中再次执行 $(this)

    顺便说一下,您似乎只需要将它作为 $(this).screenSlide(); 调用,除非您复制 id,在这种情况下它不会运行反正你期望的方式。

    Demo

    关于javascript - 将变量作为 JQuery CSS 选择器传递不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19286029/

    相关文章:

    php - 如何在zend框架2或AjaxContext中使用ajax?

    javascript - 如何控制使用 jQuery/JavaScript 提交哪些表单字段?

    jquery - 如何让 span 位于列表项中的 <a> 标记内?

    css - 无法使用 css 在列表项中设置覆盖

    css - 使用 Grunt 时无法在 Bower 组件中找到 CSS 文件

    javascript - 如何在不上传的情况下访问图像并将其显示在 IMG 标签中

    javascript - 如何获取selenium中点击事件的按钮路径

    javascript - 单选按钮矩阵组 javascript jquery

    javascript - 使用时间戳获取两个不同日期之间的时间差?

    jquery - 打印可滚动表格的全部内容