在网页中,我有 2 个不同的画廊,其中包含多个图像。每个图像都有一个分配的按钮以便删除。我决定使用带有参数的相同 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”。这是“删除文件”函数:
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”。
为什么会有这种行为?
最佳答案
请在代码中查看此行if (type="0")
。
要检查是否相等,需要为 if (type=="0")
或 if (type === "0")
。
使用=
将分配值并评估所分配的值,而==
或===
将比较两者值。
关于javascript - JavaScript 函数中令人讨厌的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28089671/