how to define variable in jquery

爱⌒轻易说出口 提交于 2020-01-30 14:21:08

问题


I would like to know how to declare a variable in jQuery

The code I am currently using is

$.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.


回答1:


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);

EDIT: 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()

given that the text box has its id attribute set to txtname. However, you don't need to use jQuery just because you can.




回答2:


Try this :

var name = $("#txtname").val();
alert(name);



回答3:


Here's are some examples:

var name = 'india';
alert(name);  


var name = $("#txtname").val();
alert(name);

Taken from http://way2finder.blogspot.in/2013/09/how-to-create-variable-in-jquery.html




回答4:


In jquery, u can delcare variable two styles.

One is,

$.name = 'anirudha';
alert($.name);

Second is,

var hText = $("#head1").text();

Second is used when you read data from textbox, label, etc.




回答5:


in jquery we have to use selector($) to declare variables

var test=$("<%=ddl.ClientId%>");

here we can get the id of drop down to j query variable




回答6:


You can also use text() to set or get the text content of selected elements

var text1 = $("#idName").text();



回答7:


var name = 'john';
document.write(name);

it will write the variable you have declared upper




回答8:


Remember jQuery is a JavaScript library, i.e. like an extension. That means you can use both jQuery and JavaScript in the same function (restrictions apply).

You declare/create variables in the same way as in Javascript: var example;

However, you can use jQuery for assigning values to variables:

var example = $("#unique_product_code").html();

Instead of pure JavaScript:

var example = document.getElementById("unique_product_code").innerHTML;


来源:https://stackoverflow.com/questions/1418613/how-to-define-variable-in-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!