我正在运行以下jquery脚本:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#textThing").blur(function(){
var isNumber = $("#textThing").val().match(/^\d+/);
$("#p2").html(isNumber);
});
});
</script>
</head>
<body>
<input type="text" id="textThing" />
<p id="p2">Paragraph 2</p>
</body>
</html>
问题是当你选择输入时,p2从不给我任何东西。我做错了什么?
答案 0 :(得分:1)
你需要说:
$("#p2").html(isNumber == null ? "" : isNumber[0]);
而不是:
$("#p2").html(isNumber);
...因为如果匹配,.match()
会返回一个数组。见这里:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/match
这是一个有效的版本:http://jsfiddle.net/k45Ka/5/
答案 1 :(得分:1)
工作演示 http://jsfiddle.net/r4VPZ/3/ 或 http://jsfiddle.net/r4VPZ/4/
您可以在上面看到.match
解释。
您还可以将.toString
与.html
或.text
api一起使用。您可以进行null
处理或查看isNaN
http://www.w3schools.com/jsref/jsref_isnan.asp
希望有所帮助,如果我错过任何事情,请告诉我,欢呼:)
好读:http://api.jquery.com/html/ &amp; http://api.jquery.com/text/
Match
:.match
返回什么:learning regex and jquery - what does .match return?
<强>码强>
$(document).ready(function(){
$("#textThing").on("blur",function(){
var isNumber = $("#textThing").val().match(/^\d+/);
$("#p2").html(isNumber.toString());
// $("#p2").text(isNumber);
});
});
//var folioIsNumResult = $("#Folio").val().match(/^\d+/i);
答案 2 :(得分:1)
演示:http://jsfiddle.net/epinapala/TbCfc/
当正则表达式不匹配时,匹配返回null!
$(document).ready(function(){
$("#textThing").blur(function(){
var isNumber = $(this).val().match(/^\d+/);
if(isNumber == null){
var res = "not a number"
}else{
var res = "valid number";
}
$("#p2").html(res);
});
});
答案 3 :(得分:0)
如果测试通过或失败,您不会创建任何文本值
DEMO http://jsfiddle.net/9MJNj/
$("#p2").html(isNumber ? 'Is number':'Is not');