JQuery事件处理程序没有触发

Dev*_*per 3 javascript jquery

请查看我的代码 -

HTML

<table>
<tr>
    <td valign="top" style="padding-top:10px;">Body :<br><br>
       <a id="expand" href="javascript:;">expand</a>
    </td>
    <td>
       <textarea rows="6" cols="30" required="required" id="message" name="message">
        </textarea>
    </td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)

jQuery的

$(function(){
       $("#expand").click(function(){                      
               $('#message').animate({"height": "300px"}, "slow" );
               $(this).attr('id','colaspe').html('colaspe');
               return false;
        });
        $("#colaspe").click(function(){
               $('#message').animate({"height": "80px"}, "slow" );
               $(this).attr('id','expand').html('expand');
               return false;
        });
});
Run Code Online (Sandbox Code Playgroud)

上面的代码在点击时工作expand.但colaspe不行.

的jsfiddle

Cod*_*ver 6

试试这个:

$(document).on('click','#expand',function(){                      
    $('#message').animate({"height": "300px"}, "slow" );
    $(this).attr('id','colaspe').html('colaspe');
    return false;
});
$(document).on('click','#colaspe',function(){
   $('#message').animate({"height": "80px"}, "slow" );
   $(this).attr('id','expand').html('expand');
   return false;
});
Run Code Online (Sandbox Code Playgroud)

工作实例

原因:您正在动态更改属性和属性.对于这样的元素,有一个.on函数将事件与jQuery中的元素绑定.所以你需要使用.on带元素的函数.


eku*_*ela 5

#colaspe当您尝试添加事件处理程序时,该按钮不存在.既可以同时创建两个按钮,也可以使用委托模式来处理点击.

https://api.jquery.com/on/