如何触发textarea中的点击事件?
我试过:
jquery
$(document).ready(function(){
$('#txtid').val('something');
$('#txtid').trigger('click');
});
html
<textarea id='txtid' rows='5' cols='20'></teaxtarea>
但是点击没有发生。代码有什么问题。
我试过这样的焦点事件
$('#txtid').focus(); //this worked
但我需要在获取到textarea的值后触发点击事件。
请帮忙..
最佳答案
您必须先设置一个点击事件处理程序。
编辑 1:由于您尝试在文档就绪中触发点击事件,因此您必须在文档就绪事件处理程序中声明点击事件处理程序,甚至在触发它之前。
HTML:
<textarea id='txtid' rows='5' cols='20'></textarea>
jQuery:
$(document).ready(function(){
$('#txtid').click(function() { alert('clicked'); });
$('#txtid').val('something');
$('#txtid').trigger('click');
});
fiddle : http://jsfiddle.net/j03n46bf/
编辑 2:
由于您希望在获得文本区域的值后触发事件,Milind Anantwar 是正确的,您必须使用 onchange 事件:
相同的 Html,不同的 jQuery:
$(document).ready(function(){
$('#txtid').change(function() { alert('Value changed'); });
$('#txtid').val('something');
$('#txtid').trigger('change');
});
fiddle :http://jsfiddle.net/sb2pohan/
编辑 3:
一些评论之后:
$(document).ready(function(){
$('#txtid').click(function() { changeDiv(); });
$('#txtid').focus(); // Set Focus on Textarea (now caret appears)
$('#txtid').val('something'); // Fill content (caret will be moved to the end of value)
$('#txtid').trigger('click'); // Click Handler will be executed
});
function changeDiv() {
// do some stuff;
}
编辑 4: 工作 test.html(在 IE、FF、Chrome 中测试):
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#txtid").click(function() { changeDiv(); });
$("#txtid").focus();
$("#txtid").val("value");
$("#txtid").trigger("click");
});
function changeDiv() {
$('#changeDiv').css("background-color","red");
$('#changeDiv').html("changed content");
}
</script>
</head>
<body>
<textarea id="txtid"></textarea>
<div id="changeDiv" style="background-color: green; width: 100px; height: 100px;">start content</div>
</body>
</html>
关于javascript - 如何触发textarea中的点击事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27424621/