繁体   English   中英

将变量传递给jQuery函数

[英]Passing a variable to jQuery function

我知道这可能很简单,但是我已经在这里阅读并尝试了很多答案,但我无法弄清楚。 如何将变量“ 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而不是两者)。

从您的代码中可以看到,您的代码应该按原样工作,因为您在调用submit之前声明了“ 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事件时定义其值,然后将其传递给函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM