[英]How do I create a text box with a submit button that performs a callback on click to a javascript function using js or jQuery?
I'm new to javascript and am having a hard time finding the answer to this. 我是javascript的新手,很难找到答案。 Any help is appreciated. 任何帮助表示赞赏。
If you had the following HTML: 如果您有以下HTML:
<input type="text" />
<input id="button" type="button" value="Click Me" />
You can bind a function to be executed when a click event fires on that button like this: 您可以绑定要在单击事件触发该按钮时执行的函数,如下所示:
$(function() {
$('#button').click(function() {
// Do logic here
});
});
You can insert the previous HTML into your document using jQuery. 您可以使用jQuery将以前的HTML插入到文档中。 First select another element in the DOM which locates where you wish to insert the HTML: 首先在DOM中选择另一个元素,该元素定位您希望插入HTML的位置:
$('#someElement')
Then you can use any of the jQuery insertion methods in order to inject some HTML of your own: 然后你可以使用任何jQuery插入方法来注入你自己的一些HTML:
$('#someElement')
.append('<input type="text" />')
.append('<input id="button" type="button" value="Click Me" />');
Now that your elements are in the DOM, you can select them and bind a callback to the click event in the normal way: 既然你的元素在DOM中,你可以选择它们并以正常方式将回调绑定到click事件:
$('#button').click(function() {
// Do logic here
});
the html : <textarea id="txt"></textarea><input type="button" id="button">submit</input>
html: <textarea id="txt"></textarea><input type="button" id="button">submit</input>
and the js: 和js:
var d = document.getElementById('button');// identifying the button
function myFunction(){
var text = document.getElementById('txt').value;//getting the user's input
// and whatever you want to do with the user's input
}
d.addEventListener('click',myFunction,false);//attaching myFunction to be called on the button click`
If you use jQuery, the syntax is a bit simpler :
如果你使用jQuery,语法有点简单:
$('#button').click(myFunction); // or $('#button').click(function(){ var text = $('#txt').val(); //and again your logic here });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.