根据要求,要实现将函数名作为参数传递,并在对应的操作下执行该函数,
eval()函数简单介绍:可计算某个字符串,并执行其中的JavaScript代码;
语法:eval(string); 参数string必须,为要计算的字符串,含有要计算的表达式或执行语句。
eval()函数实际使用:设计一个蒙版弹窗,当点击弹窗的“确定”按钮时,执行对应的函数;
<style>
.mymask{
position: fixed;
z-index: 1000;
top: 0;
right: 0;
left: 0;
bottom: 0;
background: rgba(0,0,0,.6);
}
.conDialog {
position: fixed;
z-index: 5000;
width: 35%;
max-width: 300px;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
background-color: #fff;
text-align: center;
border-radius: 3px;
overflow: hidden;
}
.dialogMessage {
padding: 1.6em .8em;
min-height: 40px;
font-size: 15px;
line-height: 1.3;
word-wrap: break-word;
word-break: break-all;
color: #999;
}
.dialogHandle {
position: relative;
line-height: 48px;
font-size: 18px;
display: -webkit-box;
display: -webkit-flex;
display: flex;
border-top:1px solid #d9d9d9;
}
.doDialog {
display: block;
-webkit-box-flex: 1;
-webkit-flex: 1;
flex: 1;
color: #3cc51f;
text-decoration: none;
-webkit-tap-highlight-color: rgba(0,0,0,0);
position: relative;
}
</style>
<div class="myDialog" id="msgDialog" style="display: none">
<div class="mymask"></div>
<div class="conDialog">
<div class="dialogMessage " id="dialogMessageCon"></div>
<div class="dialogHandle">
<input class="inputConfirm" type="hidden">
<a href="#" class="doDialog" onclick="confirmMsg(this)">确定</a>
</div>
</div>
</div>
<script>
/*打开蒙版弹窗*/
function openMyDialog( message,funName) {
$("#myDialog").fadeIn(200);
$("#myDialog").find(".dialogMessage ")[0].innerText=message;
$("#myDialog").find(".inputConfirm").val(funName);
}
/*点击确定时*/
function confirmMsg() {
$("#myDialog").fadeOut(200);
eval($("#myDialog").find(".inputConfirm").val());
}
/*点击蒙版任意位置,关闭弹窗及蒙版*/
$('.mymask').on('click', function () {
$(this).parent().fadeOut(200);
});
</script>
代码思路:打开弹窗时,传递参数及确定时要执行的函数名,将消息展示出来;同时,由于eval()函数会直接执行,所以需要将函数名存储,当点击确定时,再利用eval()函数执行该函数,实现想要的效果。