jQuery 在each() 和自定义函数方面遇到麻烦

标签 jquery function each

    $(function(){
        $(".test").each(function(){
            test();
        });
    });

     function test(){
        $(this).css("border","1px solid red").append(" checked");
    }

为什么这不起作用?我缺少什么? 这是我的测试 html:

    <p>test</p>
    <p>test</p>
    <p class="test">test</p>
    <p>test</p>

最佳答案

$(this) 不能以这种方式使用,因为您没有指定 test() 函数的上下文:

$(".test").each(function(){
        test($(this));
});

function test(el){
     el.css("border","1px solid red").append(" checked");
}

$(".test").each(function(){
      test.call(this);
});
function test(){
   $(this).css("border","1px solid red").append(" checked");
}

关于jQuery 在each() 和自定义函数方面遇到麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2176341/

相关文章:

jQuery $().each 而不是 $.each()

jquery - bootstrap 4 切换似乎在标记中起作用但在布局中不起作用

php - 向 jquery 移动站点添加数据库

ios - 函数内闭包

javascript - jQuery.contents() 获取每个元素作为 HTML/STRING

javascript - 创建数组,使用 $.each 循环,如果不在数组中则添加值

javascript - 停止在for循环中执行ajax

jquery - 模板文字格式/语法问题

c++ - 如何在不解析的情况下将重载函数指针作为参数传递 (C++03)

c - 删除链表尾部 : Why a specific approach won't work