我可以将字符串参数传递给onclick javascript函数吗



在一个脚本中,我有

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

这是由另一个脚本中的javascript评估的(这些是django中的嵌套模板(。这应该会打开一个新窗口,以便准备一个更适合打印机的网站(还有一段路要走(。


$(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的href和一个带有onclick等的javascript void函数

您可以通过两种方式来实现。您可以从元素本身调用函数,如:

<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)

最新更新