使用 jQuery 将值设置为 null

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19009387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 22:59:19  来源:igfitidea点击:

Setting value to null using jQuery

javascriptjquery

提问by Nitish

I have an Id City on page which is basically a model property. I want to set it as null. I am trying this to achieve it:

我在页面上有一个 Id City,它基本上是一个模型属性。我想将其设置为空。我正在努力实现它:

$("#City").val(null); 

But it is not setting the value to null.

但它没有将该值设置为 null。

回答by adeneo

You don't set an elements value to null, as HTML has no concept of null, undefinedetc, you remove the attribute, or better yet, set it to an empty string:

您没有设置一个元素的值null,因为HTML没有的概念nullundefined等等,你删除属性,或者更好的是,将其设置为空字符串:

$("#City").val(""); 

回答by Suresh Atta

If you are trying to set/remove Id

如果您尝试设置/删除 Id

$("#City").attr("id",""); 

or use removeAttr()

或使用 removeAttr()

If you are trying to set the value inside that ,

如果您尝试在其中设置值,

$("#City").val("");

回答by raduns

Using normal javascript , try using setAttributemethod ,

使用普通的javascript,尝试使用setAttribute方法,

document.getElementById("City").setAttribute("value" , "");

or without using the setAttributemethod,

或不使用该setAttribute方法,

document.getElementById("City").value = "";

回答by deformhead

You can remove Id using jQueryprop()or attr()methods like this :

您可以使用jQueryprop()以下attr()方法删除 Id :

$('#City').prop('id', null);

or like this :

或像这样:

$('#City').attr('id', null);

Just in case :

以防万一 :

jQuery Documentation for prop() method

prop() 方法的 jQuery 文档

jQuery Documentation for attr() method

attr() 方法的 jQuery 文档