18

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:

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

But it is not setting the value to null.

4

4 回答 4

39

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

$("#City").val(""); 
于 2013-09-25T15:45:41.413 回答
5

如果您尝试设置/删除 Id

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

或使用 removeAttr()

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

$("#City").val("");
于 2013-09-25T15:43:28.010 回答
2

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

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

或不使用该setAttribute方法,

document.getElementById("City").value = "";
于 2013-09-25T15:57:57.203 回答
0

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

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

或像这样:

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

以防万一 :

prop() 方法的 jQuery 文档

attr() 方法的 jQuery 文档

于 2013-09-25T16:15:28.267 回答