在我的index.cshtml 文件中,我有一个 razor 元素 (@Html.EditorFor),它是一个文本框。 JavaScript 无法识别该元素。如果我将元素类型更改为非 Razor 语法,则 javascript 可以看到它。我在这里缺少一些语法吗?
index.cshtml
<div class="jumbotron">
<h1>my application</h1>
@using (Html.BeginForm("Results", "Home", FormMethod.Post))
{
<div class="form-group">
//javascript can't see mainpagequery
@Html.EditorFor(model => model.SearchQuery, new { htmlAttributes = new { @class = "form-control", id = "mainpagequery" }})
@Html.ValidationMessageFor(model => model.SearchQuery, "", new { @class = "text-danger" })
//javascript can see mainpagequery in the non razor element here
<input type="text" class="form-control" placeholder="Search" id="mainpagequery">
</div>
<button type="submit" class="btn btn-default">Search</button>
}
这是我的 JavaScript。如果我使用 razor,那么“mainpagequery”会带有下划线,因为它看不到它,如果我使用 html,那就没问题。我知道我正在使用 JavaScript,因为我看到弹出警报消息。
$(document).ready(function () {
console.log("ready!");
alert("mainpage autocomplete function entered");
var input = document.getElementById('mainpagequery');
var options = {
types: ['(cities)'],
componentRestrictions: { country: "us" }
};
var mainpagequery = new window.google.maps.places.Autocomplete(input, options);
});
最佳答案
如果是 @Html.EditorFor
,您的 id 会被覆盖为模型的属性名称。
如果你使用 f12 查找元素,你会发现它如下。 (通知 ID“SearchQuery124”我刚刚将其重命名为某个名称)
所以在你的情况下进行更改,例如
$(document).ready(function () {
console.log("ready!");
alert("mainpage autocomplete function entered");
var input = document.getElementById('SearchQuery').value;
console.log(input);
var options = {
types: ['(cities)'],
componentRestrictions: { country: "us" }
};
var mainpagequery = new window.google.maps.places.Autocomplete(input, options);
});
关于javascript - document.getelementbyid 无法识别 Razor 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28620454/