2012-08-29 244 views
0
$(document).ready(function() 
    { 
     $("#cover img").click(function(event) 
     { 
      var selected_script = $(this).attr('id'); 

      //alert(selected_script); 
     //alert('#run_'+selected_script); 

      $('#run_'+selected_script).hide(); 
     }); 
    }); 

<div> 
    <img id="run_0" src="play.png" /> 
</div> 

上面的代碼在單擊時不會隱藏圖像。當我提醒時,我得到了正確的身份證號碼。單擊時隱藏元素

我錯過了什麼?

感謝

+0

是否顯示了這些警報? – hunter

+0

你想隱藏相同的圖像,你點擊? –

+3

你想隱藏什麼?你能顯示相關的HTML嗎?根據你的代碼你應該有一個id ='run_run_0' –

回答

1
$(document).ready(function() 
    { 
     $("#cover img").click(function(e) 
     { 
      $(this).hide(); 
     }); 
    }); 

<div id='cover'> 
    <img id="run_0" src="play.png" /> 
</div> 
  1. 你 'selected_script' 變種會包含id。爲什麼再加上之前的「跑步」?
  2. 您只希望#cover id中的img具有onclick。你的div(或父元素)應該有'封面'ID。
1

你是不是想掩蓋它在上面的代碼,只是做一個簡單的.hide()

$("#cover img").on('click', function(e) { 
    $(this).hide(); 

    // If you want to know why your above code isn't working, it is because you have: 
    // $('#run_'+selected_script).hide(); 
    // selected_script already has the entire ID of run_0, etc 
    // so this is outputting $('#run_run_0').hide(); why it doesn't work 

    $('#' + selected_script).hide(); // this outputs $('#run_0').hide(), and will work! 
}); 

jsFiddle Demo

1
$(document).ready(function() 
    { 
     $("#cover img").click(function(event) 
     {  
      $(this).hide(); 
     }); 
    }); 
0

你可以直接通過

$(this).hide(); 
0

這裏隱藏這就是爲什麼你的代碼是不工作:http://jsfiddle.net/prsjohnny/wp5Bs/

但(如果你是新來的jQuery)你已經有了你正在尋找的元素,那麼爲什麼再次尋找它?

這樣效率更高。

$(document).ready(function() 
{ 
    $("#cover img").click(function(event) 
    { 
     // just use $(this) instead of $('#'+selected_script) and 
     // having jquery traverse the DOM again looking for it. 
     $(this).hide(); 
    }); 
});​