除非刷新页面,否则显示/隐藏不起作用

时间:2013-09-01 22:25:35

标签: javascript jquery

编辑:为了清晰起见,我编辑了这个问题。 编辑2:我能够解决一半的问题。

以下是一个简单的脚本供用户删除他们上传的图片。

取决于是否在数据库中保存了图像。应显示切换或上传图标。

问题当点击删除按钮时,图片和切换按钮会被删除但是上传图标不会显示(除非页面被刷新)。

if (image exists in database) { 

   <div class="toggle" id="toggle<?php echo $image_id ?>"></div>
 }      
 else {
    <div class="upload_icon"  id="upload<?php echo $image_id ?>"></div>
      }

`SQL query to select image in database` 

 //this DIV expands when the toggle button is clicked

 <div class="content" id="image<?php echo $image_id ?>"><img src="<?php echo 
 $path ?>" />  
    <div class="remove content"><a href="#" id="<?php echo $image_id ?>"   
    class="delete_icon">Remove!</a></div>
 </div>

Javascript部分:

$(function(){
$('.delete_icon').on("click",function() 
{
var ID = $(this).attr("id");
var dataString = 'image_id='+ ID;
$this = $(this);
if(confirm("Are you sure you want to delete this image ?"))
{
$.ajax({
type: "POST",
url: "delete.php",
data: dataString,
cache: false,
success: function(html){

$('#image'+ID).remove()
$('#toggle'+ID).remove()
$('#upload'+ID).show();
});
}
return false;
});
});

我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

一旦您进入this函数的上下文,

success就不再是链接。我保存了this并在里面使用它,这应该可以解决问题。

此外,我不确定find实际上是否会起作用。根据您的示例,我不确定#toggle元素是否实际嵌套在.delete_icon中。

如果不是,您可能想要$('#toggle'+ID)而不是使用find。无论如何它都是一个ID选择器,所以它不会影响性能。

$(function(){
  $('.delete_icon').on("click",function() {

    var ID = $(this).attr("id"),
        dataString = 'image_id='+ ID,
        $this = $(this);

    if( confirm("Are you sure you want to remove this image ?") ) {
      $.ajax({
        type: "POST",
        url: "delete.php",
        data: dataString,
        cache: false,
        success: function(html) {

          $this.closest(".content").hide();

          $('#toggle'+ID).hide()

          $('#upload'+ID).show();

        }
      });
    }
    return false;
  });
});
相关问题