簡體   English   中英

我可以將字符串參數傳遞給 onclick javascript function 嗎?

[英]Can I pass a string argument to an onclick javascript function?

在一個腳本中,我有

<a href="javascript:void;" id="druck">

這是由 javascript 在另一個腳本中評估的(這些是 django 中的嵌套模板)。 這應該會打開一個新的 window 以准備一個對打印機更友好的站點(仍然是一個方法)。


$(function() {
    var b = document.getElementById("druck");
    b.onclick = function() {
    
        var mywindow = window.open('', 'PRINT', 'height=400,width=600');
        mywindow.document.write('<html><head><title>' + document.title + '</title>');
        mywindow.document.write('<link rel="stylesheet" href="{% static 'boot/css/bootstrap.min.css' %}" type="text/css">');
        mywindow.document.write('<link rel="stylesheet" href="{% static 'boot/css/bootstrap.css' %}" type="text/css">');
        mywindow.document.write('<link rel="stylesheet" href="{% static 'boot/css/dashboard.css' %}" type="text/css">');
        mywindow.document.write('</head><body>');

我想將第一個腳本的字符串參數傳遞給第二個腳本,這樣我也可以打印字符串。 我不適合 js,因此我想問如何將字符串傳遞給帶有 id 和 javascript void function 和 onclick 等的 href。

您可以通過 2 種方式進行操作。 您可以從元素本身調用 function,例如:

<a href="javascript:void;" onclick="myFunction ('string')" id="druck">

或者您可以使用 data-* 屬性;

<a href="javascript:void;" data-string="my string" id="druck">

而在js里面,

b.onclick = (event) => {
  let myString = event.currentTarget.dataset.string;
  //Code
}

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset

暫無
暫無

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

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