簡體   English   中英

如何動態創建按鈕並為html頁面添加onclick事件

[英]how to create button dynamically and add the onclick event for html page

我在我的javascript代碼中創建了一個按鈕,點擊此按鈕后它應該轉到product.html

var outputb2 = "<p align=right>"+ "<input type=button value=productandservices onClick=window.location=product.html>" + "</input>" +"</p>";
    $('#product').append(outputb2);

其中product是product.html中的div id。但是當我點擊這個按鈕產品和服務時......我不會去這個product.html。我能做什么..?

我不知道你為什么要使用javascript,除非你用click事件發送一些數據。 有一個簡單的HTML代碼可以做你想要的。

<a href="product.html#product">product and services</a>

如果你必須使用java-script試試這個

onclick="javascript:location.href='product.html#product'" 
var outputb2 = "<p align=right>";
outputb2 +=  "<input type='button' value='productandservices' onClick='window.location=product.html'>"
outputb2 += "</p>";

$('#product').append(outputb2);

看一下這個

<script>
var outputb2 = "<p align=right>"+ "<input type=button id='productandservices' value=productandservices >" + "</input>" +"</p>";//added id
    $('#product').append(outputb2);

    $(document).ready(function()
    {

        $(document).on("click","#productandservices",function()
        {
            alert('clcik');
            window.location='product.html';
        });

    });

</script>

要么

用引號括起文件名'

<script>
var outputb2 = "<p align=right>"+ "<input type=button id='productandservices' value=productandservices onClick=window.location='product.html' >" + "</input>" +"</p>";
    $('#product').append(outputb2);


</script>

可能你的代碼中需要一些轉義字符,它會起作用

var outputb2 = "<p 'align=right'>"+ "<input type='button' value='productandservices' onClick='window.location=\"product.html?someParam=hi\"'>" + "</input>" +"</p>";
$('#product').append(outputb2);
var outputb2 = "<p align='right'><input type='button' value='productandservices' onClick='window.location=product.html'></input></p>";
$('#product').append(outputb2);

嘗試這個 :

var outputb2 = "<p align='right'>"+ 
                 "<input type='button' value='productandservices 'onClick='window.location=\"product.html\"' />" + 
               "</p>";
$('#product').append(outputb2);

添加'像這樣: onClick='window.location=\\"product.html\\"'

現場演示

正確使用的語法:

<input TYPE="button" value=productandservices onclick="window.location.href='http://www.wherever.com'"> 

另一個選擇是在按鈕中創建一個鏈接:

<button type="button"><a href="yourlink.com">Link link</a></button>

然后使用CSS來設置鏈接和按鈕的樣式,以便鏈接占據按鈕內的整個空間(因此用戶不會錯過任何一次點擊):

button, button a{position:relative;}
button a{top:0;left:0;bottom:0;right:0;}

但鏈接的目的是轉到另一個頁面。 因此,嘗試使按鈕像鏈接一樣是錯誤的解決方案。 我的建議是你應該使用一個鏈接並將其設置為看起來像一個按鈕。

<a href="/page2>Continue</a>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM