在一个网页中,我有两个不同的画廊,里面有几张图片。每个图像都有一个分配按钮以便删除。我决定使用相同的JavaScript函数和参数来区分两个库。这些是画廊:
<div class="column col_12 gallery">
{% for testrigimage in testrigimages %}
<div id="testRigImage_{{testrigimage.id}}" class="image" align="center">
<a href="{{MEDIA_URL}}{{testrigimage.image}}"><img src="{{MEDIA_URL}}{{testrigimage.image}}" width="150" height="100" /></a>
<i id="deleteTestRigImage_{{testrigimage.id}}" class="icon-remove-sign icon-large" style="display:none;cursor:pointer;color:darkGrey;position:absolute;top:9px;left:129px;" onclick="javascript:deleteFile('{{testrigimage.id}}','0');"></i>
<br>
{{testrigimage.name}}
</div>
{% empty %}
No images have been added.
{% endfor %}
</div>
<div class="column col_12 gallery">
{% for picture in pictures %}
<div id="picture_{{picture.id}}" class="image" align="center">
<a href="{{MEDIA_URL}}{{picture.image}}"><img src="{{MEDIA_URL}}{{picture.image}}" width="150" height="100" /></a>
<i id="deletePicture_{{picture.id}}" class="icon-remove-sign icon-large" style="display:none;cursor:pointer;color:darkGrey;position:absolute;top:9px;left:129px;" onclick="javascript:deleteFile('{{picture.id}}','1');"></i>
<br>
{{picture.name}}
</div>
{% empty %}
No pictures have been added.
{% endfor %}
</div>
正如您所看到的,两个画廊都很相似。唯一的区别在于元素的“onclick”属性。为了区分两者,我向函数“deleteFile”传递了一个额外的参数:“0”或“1”。这是“deleteFile”函数:
function deleteFile(model_id, type){
var x = confirm('You are about to delete this picture. Are you sure?')
if(type="0"){
alert(type)
url = "/tests/testSetUp/testrig/" + model_id + "/delete/"
}else{
alert(type)
url = "/tests/testSetUp/pictures/" + model_id + "/delete/"
}
if (x) {
$.ajax({
type: "POST",
url : url,
data: {'csrfmiddlewaretoken': '{{ csrf_token }}'},
dataType: 'text',
success : function (data, textStatus, request) {
data = eval("(" + data + ")");
if (data.success) {
var n = noty({
text: 'Picture successfully removed.',
type: 'success',
timeout: 750,
callback:{
afterClose: function(){location.reload()}
}
});
}
else {
var n = noty({
text: 'Error. Please, contact with the administrator.',
type: 'error',
timeout: 3000
});
}
}
});
}
}
问题是始终打印(警报)“0”!当我单击第一个图库的图像(具有“0”参数的图像)时,它会发出警报0.当我单击第二个图库的图像时,它也会发出“0”警告,尽管已经指定了“1”。
为什么会这样?
答案 0 :(得分:4)
在代码if (type="0")
中查看此行。
要检查是否相等,则需要if (type=="0")
或if (type === "0")
。
使用=
将分配值并评估为分配的值,而==
或===
将比较这两个值。