我遇到的问题是我想在回调函数中使用if else语句,如下所示:
alertNotify("alert","Do you want to delete this",function(delete) {
if(delete) {
//do code
}else {
//do nothing
}
});
当前功能代码:
function alertNotify(text,type) {
$("body").append("<div id = 'alert' class='common'>\
<div id ='content'class='common'>\
</div>\
</div>");
var alert = $("<div id = 'ok' class='common'>\
Ok\
</div>\
<div id = 'cancle''class='common'>\
Cancle\
</div>");
var rename = $("<div class='common rename_it'>\
Ok\
</div>");
var type_file = $("<input type='text' id ='rename'><div id='hover'></div>");
if(type == "alert") {
$("#content").append(text);
$("#content").append(alert);
}
if(type == "rename") {
$("#content").append(rename);
$("#content").append(type_file);
}
$("#ok").click(function() {
$("div").remove("#alert");
});
$(".rename_it").click(function() {
$("div").remove("#alert");
});
$("#cancle").click(function() {
$("div").remove("#alert");
});
}
我想if语句区分是否点击#ok div或者点击#cancel div但是我不知道从哪里开始。有什么想法吗?
答案 0 :(得分:3)
您可以改为使用confirm
:
document.getElementById("prompt").onclick=function(){
if(confirm("Do you want to delete item?")){
// Delete
document.getElementById("status").innerHTML = "deleted";
}else{
// Don't delete
document.getElementById("status").innerHTML = "spared";
}
}
&#13;
<button id="prompt">delete item</button>
<div id="status"></div>
&#13;
答案 1 :(得分:0)
你可能正在尝试做这样的事情
if( confirm("Do you want to delete this")){
//delete
}else{
// do not delete
}
答案 2 :(得分:0)
在原始JavaScript中,您的代码可能类似于:
//<![CDATA[
var pre = onload;
onload = function(){
if(pre)pre(); // if previous onload run here using this type of Event handler
var doc = document, bod = doc.body;
function E(id){
return doc.getElementById(id);
}
var ok = E('ok');
ok.onclick = function(){
console.log('ok was clicked');
}
// another way to use E
E('cancel').onclick = function(){
console.log('cancel was clicked');
}
}
//]]>
答案 3 :(得分:-1)
您可以检查事件处理程序中的target
:
document.querySelector('body').addEventListener('click', function(e){
if(e.target.id === 'ok'){
alert('ok');
} else if(e.target.id === 'cancel'){
alert('cancel');
}
});
document.querySelector('body').addEventListener('click', function(e){
if(e.target.id === 'ok'){
alert('ok');
} else if(e.target.id === 'cancel'){
alert('cancel');
}
});
&#13;
div {
color: white;
display: inline-block;
text-align: center;
height: 20px;
width: 100px;
}
div#ok {
background: green;
}
div#cancel {
background: red;
}
&#13;
<div id="ok">Ok!</div>
<div id="cancel">Cancel!</div>
&#13;