有人可以解释一下为什么这段代码中的 if 语句总是返回 true:
(function ($) {
//load on page load
$(".area").load("/galleries/ #projects > li a");
//load on widget title click
$('.widget-top').live("click", function () {
$(".area").load("/galleries/ #projects > li a");
});
//stop default href from working
$('.area a').unbind().live("click", function () {
event.preventDefault();
return;
});
// variables
var i = $('#widgets-right .addinput').size() + 1;
var addDiv = $('.addinput');
//dynamic forms
$('#widgets-right .addNew').live('click', function () {
$(this).parents('.addinput').append('<div class="div_' + i + '"><h4>Reference project ' + i + '</h4><div class="gallery_one_image_wrap"><img class="gallery_one" src="" /><br/></div><p><label for="title' + i + '">Title:</label><input type="text" class="title' + i + '" name="title' + i + '" value="title' + i + '" style="width:100%;" /></p><p><label for="name' + i + '">The link:</label><input type="text" class="link' + i + '" id="name' + i + '" name="name' + i + '" value="name' + i + '" style="width:100%;" /></p><p><label for="img' + i + '">The Link to the image:</label><input type="text" class="img' + i + '" id="img' + i + '" name="img' + i + '" value="img' + i + '" style="width:100%;" /></p><a href="#" class="remNew">Remove</a></div>');
i++;
alert(i);
return false;
});
$('#widgets-right .remNew').live('click', function () {
if (i > 1) {
$(this).parent('div').remove();
i--;
alert(i);
}
return false;
});
//load into input boxes
if (i === 2) {
$("#widgets-right .area a").live("click", function () {
alert(i);
alert("this is the if ");
var title = $(this).attr('title');
$(".title").val(title);
var link = $(this).attr('href');
$(".link").val(link);
var img = $("img", this).attr('src');
$(".img").val(img);
var imgexample = $("img", this).attr('src');
$(".gallery_one").attr("src", imgexample);
});
} else {
alert("this is the else!");
}
}(jQuery));
有问题的 if/else 语句是这样的:
//load into input boxes
if ( i === 2){
$("#widgets-right .area a").live("click", function() {
alert(i);
alert("this is the if ");
var title = $(this).attr('title');
$(".title").val(title);
var link = $(this).attr('href');
$(".link").val(link);
var img = $("img", this).attr('src');
$(".img").val(img);
var imgexample = $("img", this).attr('src');
$(".gallery_one").attr("src", imgexample);
});
}else{
alert("this is the else!")
}
每当我点击#widgets-right .area a
它时,即使 i 高于 2,它总是会转到 if。为什么?克里斯