Javascript中函数自执行中使用!开头遇到的坑
2019-11-30 本文已影响0人
poipoipoi
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>正则表达式测试工具</title>
<style>
.RegExp{
width: 650px;
margin: 100px auto;
}
.RegExp h1{
color:#777;
}
.RegExp .textbox{
height: 150px;
border: 1px solid gray;
border-radius: 5px;
padding: 5px;
width: 638px;
}
.RegExp #userRegExp{
width: 215px;
padding: 5px;
border: 1px solid #cccccc;
}
</style>
<script>
window.onload = function(){
var userText = document.querySelector("#userText"),
userRegExp = document.querySelector("#userRegExp"),
userModifier = document.querySelectorAll("input[name=userModifier]"),
startBtn = document.querySelector("#startBtn"),
matchingResult = document.querySelector("#matchingResult");
startBtn.onclick = function(){
var content = userText.innerText,
regExpText = userRegExp.value,
matchingmModifier = (function(){ //A
var modifier="";
for (var i = 0;i<userModifier.length;i++){
if (userModifier[i].checked){
console.log(userModifier[i].value);
modifier += userModifier[i].value;
}
}
return modifier;
})();
console.log(regExpText);
console.log(matchingmModifier);
var regExpObject = new RegExp(regExpText,matchingmModifier);
matchingResult.innerText = content.exec(regExpObject);
}
}
</script>
</head>
<body>
<div class="RegExp">
<h1>正则表达式测试工</h1>
<textarea id="userText" class="textbox" placeholder="在此输入匹配文本"></textarea>
<p>
正则表达式:<input type="text" id="userRegExp" class="textField" placeholder="在此输入正则表达式">
<p><lable><input type="checkbox" name="userModifier" value="i">忽略大小写(ignoreCase)</lable></p>
<p><lable><input type="checkbox" name="userModifier" value="g">全局匹配(global)</lable></p>
<p><lable><input type="checkbox" name="userModifier" value="m">多行匹配(multi)</lable></p>
<input id="startBtn" type="button" value="开始匹配">
</p>
<textarea id="matchingResult" class="textbox" disabled="disabled"></textarea>
</div>
</body>
</html>
如果将A处的(function)写成!function会将该函数返回的string类型的值进行取反操作 规则在这篇文章中有讲http://cnblogs.com/boothsun/p/6016316.html 结论:在有返回值的自执行function中慎用开头慎用!