如何在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后触发click事件。
请帮忙..
您必须先设置一个click事件处理程序。
编辑1:由于您尝试触发文档就绪事件中的click事件,因此即使在触发它之前,也必须在文档就绪事件处理程序中声明click事件处理程序。
HTML:
<textarea id='txtid' rows='5' cols='20'></textarea>
jQuery的:
$(document).ready(function(){
$('#txtid').click(function() { alert('clicked'); });
$('#txtid').val('something');
$('#txtid').trigger('click');
});
小提琴: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');
});
小提琴: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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句