单击时隐藏元素

时间:2012-08-29 13:48:33

标签: jquery

    $(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>

上面的代码在点击时不会隐藏图像。当我发出警报时,我会得到正确的ID值。

我错过了什么?

感谢

5 个答案:

答案 0 :(得分: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 :(得分: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'var将包含id。为什么之前再次提前“运行”?
  2. 您只希望#cover id中的img具有onclick。你的div(或父元素)应该有'cover'id。

答案 2 :(得分:1)

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

答案 3 :(得分:0)

您可以通过

直接隐藏它
$(this).hide();

答案 4 :(得分: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();
    });
});​