2016-06-18 79 views
0

这里是我的代码简单的代码片段:textarea的值更改时是否执行了任何事件?

$("#textarea_id").on('input propertychange', function(e){ 
 
\t alert('the value of textarea changed'); 
 
}); 
 

 
$("#bold").on('click', function(e){ 
 
\t $("#textarea_id").val('bold'); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<textarea id = "textarea_id"></textarea> 
 
<br> 
 
<button id = "bold"> 
 
B 
 
</button>

我希望看到alert当textarea的值更改(以任何方式)。正如你所看到的,当我们在这个textarea中写入东西的时候,它会运行,但是当我们点击那个按钮(虽然它应该是,因为当我们点击那个按钮时,那个textarea的值会改变)。我怎样才能使它对每一种变化都很敏感?

回答

2

您可以使用change事件。但是,通过编程方式更改值不会自动触发事件处理程序。

要触发事件处理程序,可以使用trigger(event)

执行附加到给定事件类型的匹配元素的所有处理程序和行为。

还要注意:.change()仅仅是.trigger('change')

$("#textarea_id").on('input change', function(e){ 
 
\t alert('the value of textarea changed'); 
 
}); 
 

 
$("#bold").on('click', function(e){ 
 
\t $("#textarea_id").val('bold').trigger('change'); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<textarea id = "textarea_id"></textarea> 
 
<br> 
 
<button id = "bold"> 
 
B 
 
</button>

速记
相关问题