如何在jQuery中定义变量 [英] how to define variable in jquery
问题描述
我想知道如何在jQuery中声明一个变量
I would like to know how to declare a variable in jQuery
我当前使用的代码是
$.name = 'anirudha';
alert($.name);
该代码可以正常工作,但是如果我将其编写为
That code works fine, but if I write it as
$.name = document.myForm.txtname.value;
alert($.name);
然后我的代码不起作用.
Then my code does not work.
推荐答案
jQuery只是一个javascript库,在编写javascript时提供了一些额外的可用内容-因此没有理由使用jQuery声明变量.使用常规" javascript:
jQuery is just a javascript library that makes some extra stuff available when writing javascript - so there is no reason to use jQuery for declaring variables. Use "regular" javascript:
var name = document.myForm.txtname.value;
alert(name);
正如Canavar在他的示例中指出的那样,也可以使用jQuery获取表单值:
As Canavar points out in his example, it is also possible to use jQuery to get the form value:
var name = $('#txtname').val(); // Yes, it's called .val(), not .value()
假定文本框的id
属性设置为txtname
.但是,您不需要仅仅因为您可以就能使用jQuery.
given that the text box has its id
attribute set to txtname
. However, you don't need to use jQuery just because you can.
这篇关于如何在jQuery中定义变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!