jquery filtering has + not

前端 未结 5 454
离开以前
离开以前 2020-12-01 04:41

Okay I have list items, some have a span, some not.
On my event I want to add the span when they don\'t have any yet.

has() works fine, but

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-01 04:57

    $("a.add-span").click(function() {
        $("li").each(function(index) {
           if ($(this).children('span').length === 0){
             $(this).append('new span<\/span>');
           }
        })    
    })
    

    With children() method, the length property is used to check whether or not a span already exits and if it doesn't, one is added/appended.

    More Info:

    • http://api.jquery.com/length/
    • http://api.jquery.com/children/

提交回复
热议问题