jQuery:隐藏动态创建的选定DOM元素 [英] jQuery : Hide select DOM elements created on the fly

查看:294
本文介绍了jQuery:隐藏动态创建的选定DOM元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码中:

$(document).ready( function () {
    var hideInit = function () {
            $(selector1).hide();
    }
    var loadInit = function () {
            //get data
            var thingo = $('<div />');
            //populate thingo with a bunch of divs matching selector1
            $(selector2).append(thingo);
    }
    loadInit();
    hideInit();
});

我正在解析一些数据,并在loadInit中用它填充DOM,然后我希望.hide刚创建的DOM中与selector1匹配的每个元素.

I am parsing some data and populating the DOM with it in loadInit, and then I wish to .hide each of the elements present in the DOM that was just created which match selector1.

不幸的是,这些元素没有被隐藏-我在这里做错了什么?

Unfortunately the elements are not being hidden - what have I done wrong here?

谢谢!

我的选择器并不是很多人所建议的那样,但这是我调用函数的顺序.为了确保hideInitloadInit完成之后运行,我在loadInit的结尾内部调用它.

My selectors weren't incorrect, as suggested by many, but it was the order in which I was calling the functions. In order to guarantee that hideInit runs after loadInit has complete, I call it at the end, inside, of loadInit.

$(document).ready( function () {
    var hideInit = function () {
            $(selector1).hide();
    }
    var loadInit = function () {
            //get data
            var thingo = $('<div />');
            //populate thingo with a bunch of divs matching selector1
            $(selector2).append(thingo);
            hideInit();
    }
    loadInit();
});

感谢您的评论/答案!

与以下内容无关:在新创建的dom上使用jQUery hide()元素

推荐答案

这可以通过使用appendfilterhide jQuery方法处理DOM的一行代码来实现.

This can be achieved with a single line that manipulates the DOM using the append, filter and hide jQuery methods.

  1. $('selector2').append(thingo)-附加项目
  2. .filter('selector1')-原始选择器,仅选择与过滤器匹配的那些
  3. .hide()-隐藏已过滤的项目
  1. $('selector2').append(thingo) - append the items
  2. .filter('selector1') - of the original selector, only select those matching the filter
  3. .hide() - hide the filtered items

赞:

$(function()
{
    var thingo = $('<div />');
    $('selector2').append(thingo).filter('selector1').hide();
}

(可选)如果要隐藏附加项,则需要在filter之后添加一个附加链,从而可以使用find()方法,如下所示:

Optionally, if you want to hide the appended items, you'll want to add an additional chain after the filter, whereby you could use the find() method, like this:

// this will hide all child divs, so you may want to be more specific
$('selector2').append(thingo).filter('selector1').find('div').hide();

这篇关于jQuery:隐藏动态创建的选定DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆