contains选择器

有这样一个问题: 一个列表里面,很多option,但是在不知道value,只知道他的内容的时候,怎么进行选择,比如:

北京市天津市上海市重庆市

在不知道他的value和index的时候,选择北京市,能否实现,怎么操作? 实现的方法呢: 第一个是常规的:

$('select option').filter(function(){

  return
this.text === '北京市'
});

然而jQuery 里面还有个选择器叫做:contains()。

 $("select option:contains('北京市')")

这样就直接选到了想要的。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>contains demo</title>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<div>John Resig</div>
<div>George Martin</div>
<div>Malcom John Sinclair</div>
<div>J. Ohn</div>
 
<script>
$( "div:contains('John')" ).css( "text-decoration", "underline" );
</script>
 
</body>
</html>

结果是:

John Resig
George Martin
Malcom John Sinclair
J. Ohn
posted @ 2015-08-24 11:50  Skylor.min  阅读(284)  评论(0编辑  收藏  举报