×

JS里的[attribute ^ = value]选择器

作者:andy0012019.12.09来源:Web前端之家浏览:8262评论:0

jQuery的[attribute^=value]选择器用于选取每个带有指定属性且以指定字符串开头的元素。

语法:

$("[attribute^='value']")

参数:

● attribute:用于指定需要选择的属性(任何html元素),不可省略。

● value:用于指定属性值以其开头的字符串,不可省略。

返回值:返回所有选定元素的数组。

示例1:使用[attribute ^ = value]选择器选择类名以top开头的元素

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<style type="text/css">
			div {
				width: 50px;
				height: 50px;
				background-color: yellow;
				margin: 20px;
				float: left;
			}
		</style>
	</head>

	<body>
		<div class="top">One</div>
		<div class="top-only">Two</div>
		<div class="top second-class">Three</div>
		<div class="first top">Four</div>
		<div class="first top third">Five</div>
		
		<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
		<script>
			$(document).ready(function() {
				var select = $("[class^='top']");
				select.css({
					background: "red"
				});
			});
		</script>
	</body>
</html>

示例2:选取所有 name 属性以 'nation' 为开头的 input 元素

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
		<script>
			$(document).ready(function() {
				$("input[name^='nation']").css("background-color", "yellow");
			});
		</script>
	</head>

	<body>
		<p>选取所有 name 属性以 'nation' 为开头的 input 元素。</p>
		<input name="nationality" type="text" value="Chinese">
		<input name="nation" type="text" value="English">
		<input name="country" type="text" value="Germany">
		<input name="anothernation" type="text" value="Norwegian">
	</body>

</html>

您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/js2938490283490820984.html

网友评论文明上网理性发言 已有0人参与

发表评论: