本文介绍了如何使用jquery动态添加按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的任务是动态地向div添加按钮..这是我按照动态添加按钮的代码,但它不起作用请给我一个解决方案
My task is to add button dynamically to the div.. here is the code that i follow to add button dynamically but its not working please give me a solution for this
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function test() {
var r = "$('<input/>').attr({
type: "button",
id: "field"
})";
}
$("body").append(r);
</script>
</head>
<body>
<button onclick="test()">Insert after</button>
</body>
</html>
在页面加载时附加div的代码,但不能正常工作
code to append button on div when page loads but its not working
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
function test() {
var r=$('<input/>').attr({
type: "button",
id: "field"
});
test().append("#test");
}
</script>
</head>
<body>
<div id="test"></div>
<button id="insertAfterBtn" onclick="test()">Insert after</button>
</body>
</html>
推荐答案
您的追加行必须在<$ c $中c> test()功能
编辑:
以下是两个版本:
版本1:jQuery监听器
$(function(){
$('button').on('click',function(){
var r= $('<input type="button" value="new button"/>');
$("body").append(r);
});
});
DEMO HERE
版本2:使用功能(如您的示例)
function createInput(){
var $input = $('<input type="button" value="new button" />');
$input.appendTo($("body"));
}
DEMO HERE
注意:这个可以用完成。 appendTo
或 .append
。
这篇关于如何使用jquery动态添加按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!