div id包含length为零

时间:2016-01-11 21:50:14

标签: javascript jquery html

我正在检查Div id包含。如果该Div存在则显示另一个显示或隐藏的div。

如果我使用完整div,则id显示1,否则总是为零。

$(function () {
  alert($('div[id="dnn_ctr2555_DNNWebControlContainer_ctl01_SPE_MBRDemographicsControl_pnlDemographics"]').length);
  if ($('div[id^="_SPE_MBRDemographicsControl_pnlDemographics"]').length) {
    /* it exists */
    $('#DemographicCntrlContent').show();
  }
  else {
    /* it doesn't exist */
    $('#DemographicCntrlContent').hide();
  }
})

我的if条件有什么不妥。

2 个答案:

答案 0 :(得分:4)

[attr^=abc]检查 abc

开头的属性

[attr$=abc]检查结尾的属性<{1}}

abc检查包含字符串的属性 [attr*=abc]

abc检查等于 [attr~=abc]的属性 - 所以abc不会匹配,但hello abcd

hello abc检查 [attr|=abc]abc的属性,即确切的单词abc-...abc后跟{{ 1}}(然后是任何东西)

答案 1 :(得分:1)

您正在使用carat(^)符号,这基本上意味着'以'开头'。如果您想查找包含,可以使用div[id*=

if ($('div[id*=""]').length)

另一种检查方法是通过.contains()选择器:

if($("div").attr("id").contains('_SPE_MBRDemographicsControl_pnlDemographics')) // return true - false