标签过滤

时间:2014-01-01 23:42:25

标签: javascript

我想过滤标签以搜索“1125”,如果它不存在,它会显示一个警告框。所以这是我的代码:

if (var id = $('mobilelabel_2:contains("1125")').attr('for');)
{
    alert ("works");
}
else
{
    alert ("try again");
}

3 个答案:

答案 0 :(得分:0)

您必须使用.#字符来表示idclass选择器:

  if ($('#mobilelabel_2:contains("1125")').length > 0)
  {
      alert ("works");
  }else{
      alert ("try again");
  }

HTML

<label id="mobilelabel_2">Test 1125</label>

另请注意if条件的修订语法。无需选择for属性并将其存储到变量中。相反,您可以使用length属性检查包含1125的元素是否存在。

JS小提琴: http://jsfiddle.net/8R98b/

答案 1 :(得分:0)

提示,在此处发布代码之前,始终通过jshintjslint

运行代码

通过jshint运行您的代码会收到以下11个警告!

1   Expected an identifier and instead saw 'var'.
1   Expected ')' to match '(' from line 1 and instead saw 'id'.
1   Expected an identifier and instead saw '='.
1   Expected an assignment or function call and instead saw an expression.
1   Missing semicolon.
1   Expected an identifier and instead saw ')'.
1   Expected an assignment or function call and instead saw an expression.
1   Missing semicolon.
5   Expected an identifier and instead saw 'else'.
5   Expected an assignment or function call and instead saw an expression.
5   Missing semicolon

我想你可能会写:

if ($('#mobilelabel_2:contains("1125")').length > 0)//ele with id mobilelabel_2 contains text 1125
{
    alert ("works");
}
else
{
    alert ("try again");
}

答案 2 :(得分:0)

我修复了你的代码,我觉得JQuery ..?

if (var id = $("#mobilelabel_2:contains('1125')").attr('for')
{
    alert ("works");
}
else
{
    alert ("try again");
}