jQuery添加标签
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script> <script> $(function () { $("#add").click(function () { if ($("#which").val() != "0") { var tag = $("#which").find("option:selected").text(); if ($("#content").children("span").length < 3) { //添加标签的个数限制 if ($("#content").text().indexOf(tag) < 0) {//不重复添加标签 $("#content").append("<span class='t' onclick='Del(this)'>" + tag + "</span>"); $("#message").text(""); } else { $("#message").text("您已经添加过此标签!"); } } else { $("#message").text("最多添加3个标签!"); } } }) Del = function (obj) { obj.remove(); } }) </script>
也可以换种写法
$("#add").click(function () { var len = $(".content ul li").length; if (len < 3) { var a = $("#select").find("option:selected").text(); if (a != "请选择") { for (var i = 0; i < len; i++) { var b = $(".content ul li").eq(i).text(); if (a == b) { alert("不能重复添加"); return; } } $(".content ul").append("<li onclick='del(this);'>" + a + "</li>"); } } else { alert("选择不能超出3个"); } });
<body>
<span id="message"></span>
<div id="content">
</div>
<div>
<select id="which">
<option value="0">请选择</option>
<option value="1">你妹</option>
<option value="2">快点说</option>
<option value="3">爱</option>
<option value="4">我</option>
</select>
<input id="add" type="button" value="添加" />
</div>
</body>
浙公网安备 33010602011771号