![](/img/trans.png)
[英]How to create a link tag dynamically with onclick event attribute in php
[英]How to Dynamically Create a Submit Button with an “onclick” Event Attribute?
我編寫了以下代碼,以便產生一個動態的提交按鈕,單擊該按鈕將發送電子郵件,但是它不起作用。
function createbuttomdyanmic()
{
var button = document.createElement('input');
button.setAttribute('type', 'submit');
button.setAttribute('ID', 'btnSendMail');
button.setAttribute('value', 'Send Mail');
button.setAttribute('onclick', 'btnSendMail_Click');
document.body.appendChild(button);
button.setAttribute("class", "btn btn-primary");
$('#button').addClass('myClass');
}
另外,我需要添加此樣式,但它也不會出現。
margin-left:1407px;
width:98px;
您的代碼中有些問題需要修復:
setAttribute()
方法設置事件處理程序。 您可以像這樣使用addEventListener() :
button.addEventListener('click', btnSendMail_Click);
或者像這樣的onclick
:
button.onclick = function(){
btnSendMail_Click()
};
setAttribute("class")
。 像這樣:
button.classList.Add("btn", "btn-primary");
button
不屬於任何form
,則只需要使用type="button"
,否則只需將其放在form
元素中,因為通常使用submit
按鈕來提交表單。 實際上,該代碼運行得很好,僅作了一些更正和建議,如下所示:
擁有提交按鈕意味着它應該是表單的元素,盡管您可以使用“ form”屬性使用HTML5將其放置在表單之外。
鑒於這是jQuery的唯一一行,並且它引用的是ID為“ button”的元素,而提交按鈕的ID為“ btnSendMail”,因此下一部分代碼似乎是多余的,因此我將其注釋掉:
//$('#button').addClass('myClass');
創建動態提交按鈕的函數名稱似乎有錯字。 如果您在代碼中不打錯地調用該函數,則該函數將不會執行。 因此,在清除名稱之前,我刪除了該名稱,將其完全轉換為匿名函數。
使用setAttribute()設置onclick事件屬性的值沒有錯。 另一種方法是使用addEventListener();。 兩者都可以在Google Chrome中正常運行,只不過setAttribute()是兩者中比較快的一個; 看這里 。 盡管通常使用提交按鈕來提交表單,但是只要您提供一個“ formaction”屬性(如果您希望將瀏覽器重定向到url,即使是JavaScript url也可以),它都具有一定的靈活性!
最后,您提供了CSS代碼,但未指明它應屬於哪個類,因此我自由地將其轉換為.btn類的樣式。 我還更改了代碼,以使我的老式顯示器幾乎看不見按鈕。 我也添加了一些顏色以使按鈕突出以進行測試。
function btnSendMail_Click() { console.log('Button clicked; email sent'); } (function() { var button = document.createElement('input'); button.setAttribute('type', 'submit'); button.setAttribute('ID', 'btnSendMail'); button.setAttribute('value', 'Send Mail'); button.setAttribute('onclick', 'btnSendMail_Click()'); button.setAttribute('form', 'myform'); document.body.appendChild(button); button.setAttribute("class", "btn btn-primary"); button.setAttribute("formaction", "javascript: console.log('bye');") //$('#button').addClass('myClass'); }());
.btn { margin-left: 207px; width: 98px; height: 48px; background: red; color: #fff; }
<form id="myform"> </form>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.