2017-08-04 32 views
-2

錯誤消息:無法設置屬性'innerHTML'爲null。爲Mailto設置HREF:

我注意到問題是href="mailto:<a id="Email">...是在"",但我怎麼能改變電子郵件ID而不移動郵件到JavaScript?或者是可能的。

我知道用JavaScript有鏈接編碼,但在HTML中有相同嗎? (例如:href='mailto:'<a id="Email">'...

function Email_Address() { 
 

 
    var emailaddress = document.getElementByID("EmailAddress").value; 
 
    document.getElementById("Email").innerHTML = emailaddress; 
 

 
}
Email Address: <input type="text" id="EmailAddress" onkeyup="Email_Address()" onchange="Email_Address()"> 
 
<br> 
 
<br> 
 
<a href='mailto:<a id="Email">?subject=Test&body=This%20is%20Test'><button>Email</button></a>

+4

爲什麼會出現在href內的錨標記:

現在,在JavaScript中,你可以使用它id像這樣訪問它上面的修改錨元素? – epascarello

+1

您的定位標記無效 – Matthew

+0

正確的語法是'[email protected]'。 –

回答

1

您必須在javascript中設置整個href標記。你不能用HTML做到這一點。請嘗試以下操作:

Email Address: <input type="text" id="EmailAddress" onkeyup="Email_Address()" onchange="Email_Address()"> 
<br> 
<br> 
<a id="anchorMail"><button>Email</button></a> 

而且在JS:

function Email_Address() { 
    var emailaddress = document.getElementByID("EmailAddress").value; 
    document.getElementById("anchorMail").href = 'mailto:'+ emailaddress +'?subject=Test&body=This%20is%20Test'; 
} 
+0

謝謝,這應該工作。 –

1

你不能把屬性值中的元素

把ID你已經錨開始標記

使用字符串替換。改變電子郵件地址

<a id="Email" href='mailto:PLACEHOLDER?subject=Test&body=This%20is%20Test'> 

document.getElementById("Email").href = 
    document.getElementById("Email").href.replace("PLACEHOLDER", emailaddress); 

注意:<a>內不能有<button>。由於您正在鏈接到一個URL,請使用<a>。如果你想讓它看起來像一個按鈕,就使用CSS。

0
<a href='mailto:<a id="Email">?subject=Test&body=This%20is%20Test'><button>Email</button></a> 

的代碼上面這條線是無效HTML,因爲anchor tag specification,你可以把你的時間閱讀,也可以隨意跳到mailTo部分。

所以爲了使你的代碼有效:我

<a href='mailto:[email protected]&subject=Test&body=This%20is%20Test' id="email">Email</a> 

注意如何從<a>標籤中取出<button>標籤。這是因爲它是不必要的,你可以使用CSS來修改上面的錨點標籤ID #email,使它看起來像一個按鈕。有很多非常有用的在線參考資料可以幫助您實現這一目標。

function Email_Address() { 
    // grabbing the value of an element with ID of `EmailAddress` 
    var emailAddress = document.getElementByID("EmailAddress").value; 
    // setting the value of `emailaddress` to the element with ID of `email`. 
    document.getElementById("email").innerHTML = emailAddress; 
}