当使用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>