简体   繁体   English

如何在单击事件函数中更新Javascript全局变量

[英]How to update Javascript global var inside a click event function

Using Javascript & jQuery, I'm trying to get the mouse coordinates of a click event to use in other Javascript functions. 使用Javascript和jQuery,我试图获取click事件的鼠标坐标以用于其他Javascript函数。 My problem is that global variables set within an event function do not seem to update outside the function, like global vars within other functions. 我的问题是在事件函数中设置的全局变量似乎不在函数外部更新,就像其他函数中的全局变量一样。 For example, if I have the following global variable declaration and event function to track mouse coordinates in a div with ID "clickable_area": 例如,如果我有以下全局变量声明和事件函数来跟踪ID为“clickable_area”的div中的鼠标坐标:

var mouseXPos = 0;
var mouseYPos = 0;
$(document).ready(function(){
  $("#clickable_area").click(function(e){
    mouseXPos = e.pageX;
    mouseYPos = e.pageY;
  });
});

...unless I put all code that deals with mouseXPos and mouseYPos into the event function itself, these 2 variables are not updated and available outside the event function until after the next event. ...除非我将所有处理mouseXPos和mouseYPos的代码放入事件函数本身,否则这两个变量在事件函数之外不会更新并且在下一个事件之后可用。 For example: 例如:

function displayCoordinates() {
console.log("mouseXPos = " + mouseXPos + " and mouseYPos = " + mouseYPos);
}

...yields: ...收益率:

>>mouseXPos = 0 and mouseYPos = 0

Any suggestions on how to get these 2 global vars to update outside the function once it has been triggered, or am I just running up against an inherent design demand of Javascript? 关于如何在触发函数后让这两个全局变量更新到函数外的任何建议,或者我是否只是遇到Javascript的固有设计需求? Could I use a callback queue to facilitate this? 我可以使用回调队列来促进这个吗? I could track the "mousemove" event instead and it works fine, but I don't want the overhead of constantly tracking mouse movement. 我可以跟踪“mousemove”事件而且它工作正常,但我不希望不断跟踪鼠标移动的开销。

If you insist on using Global Variables (bad idea in my opinion) try this. 如果你坚持使用全局变量 (在我看来是个坏主意)试试这个。 Asign them as window.mouseXPos = 0 , then recall them simply as mouseXPos . 将它们设置为window.mouseXPos = 0 ,然后将它们简单地称为mouseXPos However, assigning them outside the scope of function load should make them global, using window. 但是,将它们分配到函数加载范围之外应该使用window.使它们全局化window. will ensure such. 将确保这样。

See my example: 看我的例子:

jsFiddle 的jsfiddle

JS JS

<script type="text/javascript">
    window.mouseXPos = 0;
    window.mouseYPos = 0;

    $(function() { // <-- Same as `$(document).ready(function(){`
        $(document).on('click', '#clickable_area', function(e) {
            mouseXPos = e.pageX;
            mouseYPos = e.pageY;
        });
    })
</script>

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

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