gpt4 book ai didi

javascript - 如何通过javascript动态添加新按钮

转载 作者:行者123 更新时间:2023-11-28 14:59:39 27 4
gpt4 key购买 nike

我有两个文本框和一个按钮,我想添加一个新的文本字段,当我单击按钮时,它应该显示来自 textbox1 的卡片名称和来自 textbox2 的链接 URL

//AddnNewCardNavigator
var counter=2;
var nmecardtxt= document.getElementById("textbox1").value;
var linkurltxt= document.getElementById("textbox2").value;
$("#addbutton").click(function(){
if(nmecardtxt ==""||nmecardtxt ==0||nmecardtxt ==null
&& linkurltxt ==""||linkurltxt ==""|| linkurltxt ==0||linkurltxt ==null){
alert("Please insert value in Card name and Link Url textboxes and must be correct");
return false;
}
var NewCarddiv = $(document.createElement('div')).attr("id",'cardlink'+counter);
NewCarddiv.after().html()
})
</script>
<!-- text boxes-->
<div class="row">
<div class="col-md-12">
<div id="textboxesgroup">
<div id="textboxdiv1">
<label style="color:blanchedalmond">Card Name: </label><input type="textbox" id="textbox1">
</div>
<div id="textboxdiv2">
<label style="color:blanchedalmond">Link Url:&ensp;&ensp;&ensp; </label><input type="textbox" id="textbox2">
</div>
</div>
</div>
</div>

最佳答案

您的变量 nmecardtxtlinkurltxt 必须在点击函数内部创建,
因为在加载页面时它是空的。

我还冒昧地为这些变量使用 jQuery,因为您已经在使用它,并尝试增强其他一些东西:
(有关详细信息,请参阅我的代码中的注释)

//AddnNewCardNavigator
var counter = 2;

// On click function
$("#addbutton").click(function() {

// Here it's better
var nmecardtxt = $("#textbox1").val();
var linkurltxt = $("#textbox2").val();

// Modified you test here
if (!nmecardtxt || !linkurltxt) {
alert("Please insert value in Card name and Link Url textboxes and must be correct");
return false;
}

// Modified creation of the card
var link = $(document.createElement('a')).attr("href", linkurltxt).html(linkurltxt);
var NewCarddiv = $(document.createElement('div')).attr("id", 'cardlink' + counter).html(nmecardtxt + ": ").append(link);
$('#cards').append(NewCarddiv);
//NewCarddiv.after().html(); // Was that line an attempt of the above ?
});
body {
background: #888;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- text boxes-->
<div class="row">
<div class="col-md-12">
<div id="textboxesgroup">
<div id="textboxdiv1">
<label style="color:blanchedalmond">Card Name: </label><input type="textbox" id="textbox1">
</div>
<div id="textboxdiv2">
<label style="color:blanchedalmond">Link Url:&ensp;&ensp;&ensp;</label><input type="textbox" id="textbox2">
</div>
</div>
</div>
</div>

<!-- Added the below -->
<div id="cards">
</div>
<button id="addbutton">Add…</button>

希望对您有所帮助。

关于javascript - 如何通过javascript动态添加新按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50469549/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com