简体   繁体   English

如何在jQuery函数之外获取click事件值

[英]How to get the click event values outside the function in jQuery

How can I get the onclick event (this value change when click on div) in jQuery? 如何在jQuery中获取onclick事件(单击div时此值更改)?

$("ul li").click(function(){
  var v = $(this).val();
});

$(function(){
  alert(v);
});
$(function() {

    var v;

    $('ul li').click(function() {
        v = $(this).val(); // .text() - consider
        testFunction();
    });

    function testFunction() {
        alert(v);
    }

});

Your issue was variable scope, you were defining a variable only available to the click function. 您的问题是变量范围,您正在定义仅适用于click函数的变量。 If you define it outside of the function it will be available to other in scope functions. 如果在函数外部定义它,它将对其他作用域函数可用。

Here's a demo: 这是一个演示:

http://jsfiddle.net/vs87B/ http://jsfiddle.net/vs87B/

You might want to consider using .text() instead of .val() 您可能要考虑使用.text()而不是.val()

as I understand that you want to change the text of a div 据我了解,您想更改div的文本

your div is as follow 您的股利如下

 <div>123</div>

you can do it as 你可以做到

<script>

$("div").click(function () {
 $(this).replaceWith( "new text " );
});
</script>

EDIT you can use global variable as follow 编辑您可以使用全局变量,如下所示

 $.mynamespace = {};
$("ul li").click(function(){
       $.mynamespace.myVar  = $(this).val();
});

$(function(){
  alert( $.mynamespace.myVar );
});

refer How to store a global value (not necessarily a global variable) in jQuery? 请参阅如何在jQuery中存储全局值(不一定是全局变量)?

如果您的意思是单击时获取div的innerHTML,那么以下代码可以帮助您

$("div").click(function(){console.log($(this).html())})

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

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