jquery 表單對象屬性過濾器 :selected的空格問題

當使用jquery表單屬性選擇器選擇全部selected元素時,如$("select:selected"),這一表達式是無效的,由於真正被選擇的是<select>下的<option>元素,這時想定位selected的option元素,可寫成$("option:selected")或$("select :selected")即select後:前加一空格。javascript

源碼以下:html

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<script type="text/javascript" src="jquery/jquery-2.2.0.min.js"></script>

<script type="text/javascript">
	$(function() {
		$("select").change(function() {
			var str = "";
			// $("select option:selected").each(function() {
			// $("option:selected").each(function() {
			$("select :selected").each(function() {
			//若是寫成option的父元素select,則要加個空格,即select :selected
				str += $(this).text();

			});
			$("div:last").html(str);
		});
		$("checkbox").change(function() {
			var str = "";
			// 			$("select option:selected").each(function() {
			// 			$("option:selected").each(function() {
			$("input :selected").each(function() {
			//若是寫成真正選擇的option的父元素select,則要加個空格,即select :selected
				str += $(this).text();

			});
			$("div:last").html(str);
		});

	});
</script>
</head>

<body>
	<form id="form">
		beijing:<input type="checkbox" value="beijing" />
		shanghai:<input type="checkbox" value="shanghai"/>
		guangzhou:<input type="checkbox" value="guangzhou"/><br>
		<select>
			<option disabled selected>請選擇一個城市</option>
			<option>北京</option>
			<option>上海</option>
			<option>廣州</option>
			<option>杭州</option>
		</select>
		
		<div id="one" style="width:100px;height:150px;border:solid red;">
			<div>div one</div>
			<div>div two</div>
			<div>div three</div>
			<div>div four</div>
		</div>
		<div id="two">div id two</div>
		<div id="three"></div>
		<div style="width:50px;height:20px;border:solid green"></div>
	</form>
</body>
</html>
相關文章
相關標籤/搜索