如何使用innerHTML根据用户的输入创建可点击链接?

时间:2017-11-10 03:08:17

标签: javascript html

我想提示用户输入网站,然后将该网站显示在页面上作为可点击链接。有人可以帮我弄清楚为什么这不起作用吗?

HTML:

<h5 class="user-output">My favorite website is <span id="favorite-
website">...</span></h5>

<button class="button-primary" onclick=app.setWebsite()>Set 
Website</button>

当用户点击“设置网站”时,会弹出一个带有提示的对话框,但是下面的代码没有显示任何框。

JS:

app.setWebsite = function setWebsite() {
var favWebsiteInput = prompt("What is your favorite website?")
var getWebsite = document.getElementById("favorite-website")
getWebsite.innerHTML = <a href="favWebsiteInput">
  <span class="favorite-website"></span>find out here!</a>

3 个答案:

答案 0 :(得分:2)

HTML:

<h5 class="user-output">My favorite website is
    <span id="favorite-website">...</span>
</h5>

<button class="button-primary" onclick="app.setWebsite()">Set Website</button>

JS:

app = {};
app.setWebsite = function() {
    var favWebsiteInput = prompt("What is your favorite website?");
    var getWebsite = document.getElementById("favorite-website");

    getWebsite.innerHTML = '<a href=http://' + favWebsiteInput + '>find out here!</a>';
};

答案 1 :(得分:0)

此代码可以使用。

if(!app)app = {};
app.setWebsite = function setWebsite() {
    var favWebsiteInput = prompt("What is your favorite website?")
    var getWebsite = document.getElementById("favorite-website")
    getWebsite.innerHTML = '<a href="favWebsiteInput"><span class="favorite-website"></span>find out here!</a>';
}

答案 2 :(得分:0)

 app.website = function setWebsite()
{
  var favWebsite =  document.getElementById('favourite-website');
     favWebsite.addEventListener("click", function(){
        favWebsite.innerHTML = `<a href="`+favWebsiteInput+`">
  <span class="favorite-website"></span>find out here!</a>`;
    });
}