javascript - 将变量传递给 jQuery 函数
问题描述
我知道这可能很简单,但我在这里阅读并尝试了一堆答案,但我无法弄清楚。如何将变量“booklink”传递给 jQuery 函数?
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btns = document.querySelectorAll('.ebtn');
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
[].forEach.call(btns, function(btn) {
btn.onclick = function(event) {
modal.style.display = "block";
var booklink = jQuery(this).attr("data-id");
console.log(booklink);
// on submit open book link
jQuery('#mc4wp-form-1').submit(function () {
window.open(booklink);
})
}
})
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
解决方案
从我可以看到你正在使用 jQuery 和 vanilla javascript 的混合,这不是一件坏事,但它可能会在未来让事情变得混乱,尝试坚持一种风格(即 jQuery 或 vanilla javascript 不是两者)。
从我从您的代码中可以看出,您的代码应该按原样工作,因为您在调用提交之前声明了“booklink”变量。
我已经开始整理您的代码以匹配所有 jQuery 并稍微修改它应该有助于传递“booklink”值。
// Get the modal
var modal = jQuery("#myModal");//return matching elemetns id(s) of #myModal
// Get the button that opens the modal
var btns = jQuery('.ebtn');//return matching elements with class(es) of .ebtn
//Declare booklink out of the event
var booklink = "";
$('.ebtn').on('click', function(event){
modal.css('display','block');
//Update booklink when processing the click event
booklink = jQuery(this).attr("data-id");
//Call the function to submit the form and open a new window
openBookLink(booklink);
});
// When the user clicks on <span> (x), close the modal
$('.close').on('click', function(){
modal.css('display','none');
})
// When the user clicks anywhere outside of the modal, close it
$(window).on('click', function(event) {
if (event.target == modal) {
modal.css('display','none');
}
});
function openBookLink(booklink){
jQuery('#mc4wp-form-1').submit(function () {
//This should match what booklink was set to above
window.open(booklink);
})
}
主要更改是在事件之外声明 booklink 变量,并在处理 click 事件时定义它的值,然后将其传递给函数。
推荐阅读
- python - 无法定位元素,alt src 图片链接
- python - 有没有办法创建一个数组,其值由另一个数组的值决定?
- c - c语言中使用sscanf将字符串拆分为int和char两个变量
- google-cloud-firestore - 我们什么时候从 Firestore 收到此错误“无法写入文档,因为它超出了允许的最大大小。”
- vert.x - Vertx 内置 ClusterHealthCheck 程序阻塞 vertx 线程
- java - 如何在 M1 Macbook 上编译 OpenJDK 11?
- sql - FAILED: SemanticException Line 0:-1 Unsupported SubQuery Expression yyyy-MMM-dd: 只允许作为顶级连接的子查询表达式
- reactjs - .Net 核心和 React uppy.io 110mb 文件上传异常“请求内容意外结束”。
- node.js - $lookup 查找数组中的 ObjectId 并将其投影到同一个数组
- powershell - 如何修改这个 PowerShell 脚本?