[英]Jquery .val() function not working on global scope
I have four radio buttons inside the div and want to store the value of the selected checkbox into a jquery variable.我在 div 中有四个单选按钮,并希望将所选复选框的值存储到 jquery 变量中。 However the code is working fine inside the button scope.
然而,代码在按钮 scope 内运行良好。 However if i declare the variable on the global scope(outside the button scope),the variable returns undefined Here is the jquery code that works fine
但是,如果我在全局范围(按钮范围之外)声明变量,则变量返回undefined这是运行良好的 jquery 代码
$(document).ready(function(){
$('button').click(function(){
var x=$('[name=user]:checked').val();
alert(x);
});
});
Here is the html code associated with it这是与之关联的 html 代码
<div class="first-section">
<input type="radio" name="user" value="one">1</input>
<input type="radio" name="user" value="two">2</input>
<input type="radio" name="user" value="three">3</input>
<input type="radio" name="user" value="four">4</input>
<button class="submit-one">Submit</button>
</div>
How to reuse this x variable in global scope.如何在全局 scope 中重用这个x变量。 On declaring global it returns undefined.
在声明全局时,它返回未定义。 Here is the problematic code.
这是有问题的代码。
$(document).ready(function(){
var x=$('[name=user]:checked').val();
$('button').click(function(){
alert(x);
});
});
//returns Undefined
you can declare global value x
and then change it's value with in your function (in your example in.click() function)您可以声明全局值
x
,然后在 function 中更改它的值(在您的示例中为 in.click() 函数)
$(document).ready(function(){
var x
$('button').click(function(){
x=$('[name=user]:checked').val();
alert(x);
});
});
You're declaring a variable inside a function, so it will not be accessible outside of the function.您在 function 中声明了一个变量,因此在 function 之外无法访问它。
If you want to access x
outside of the function somewhere else you need to declare it outside of the function eg如果您想在 function 之外的其他地方访问
x
,您需要在 function 之外声明它,例如
var x;
$(document).ready(function(){
$('button').click(function(){
x = $('[name=user]:checked').val();
alert(x);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.