<!doctype html> <html> <head> <meta charset="utf-8"> <title>input一键删除value值</title> <script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script> <style> /*input_box*/ .input_box { width: 640px; margin: 20px auto 0 auto; } .input_box .input_content { width: 620px; margin: 10px auto 0 auto; } .input_box .input_content input { width: 618px; height: 60px; text-indent: 20px; font-family: "Microsoft YaHei"; font-size: 24px; letter-spacing: 0; color: #656565; background-color: #f7f7f7; font-weight: normal; line-height: 60px; border-radius: 4px; border: 1px solid #cecece; } .input_box .test { display: none; width: 620px; margin: 10px auto 0 auto; } .input_box .test span { font-family: "Microsoft YaHei"; font-size: 20px; font-weight: normal; color: #ff2121; line-height: 20px; } .input_box_mistake { background-color: #f6d425; padding-top: 10px; padding-bottom: 10px; } .input_box_mistake .test { display: block; } </style> </head> <body> <div class="form_box"> <div class="input_box input_box_mistake"> <div class="input_content"> <input type="text"> </div> <div class="test"> <span>此处为必填,请输入数据</span> </div> </div> </div> <script> //input加上删除按钮 var $inputText = $("input[type='text']"); $inputText.css({ "width": "560px", "padding-right": "60px" }); $inputText.parent().css({ "position": "relative" }); $inputText.keyup(function() { $(this).change(); }); $inputText.change(function() { if ($(this).val() != "" && $(this).parent().find("span").length <= 0) { // console.log("改变了"); var $mThis = this; $(this).parent().append( " <span class='clear_btn' style='display:block;width:60px;height: 60px;background:url(http://www.jq22.com/tp/2e6f628a-258a-46db-827e-06f79ca8e032.png) no-repeat center;position: absolute;top: 0;right:0;'></span>" ); $(".clear_btn").click(function() { $(this).parent().find("input").val(""); $(this).remove() }); } else if ($(this).val() == "" && $(this).parent().find("span").length > 0) { $(this).parent().find("span").remove(); } }); </script> </body> </html>