gpt4 book ai didi

Javascript 未在 MVC Razor View 中运行

转载 作者:行者123 更新时间:2023-12-03 06:44:11 25 4
gpt4 key购买 nike

我是 javascript 新手,无法弄清楚为什么当 IsImportant 为 true 时没有将图像的可见性设置为正常。通过检查页面,我可以看到 if 语句填充了 true 或 false,但它不会影响可见性。

感谢任何帮助,谢谢

@using DomainLayer.DTOs
@model MessageDto

<script type="text/javascript">
function setImportantFlag()
{
if (@Json.Encode(Model.IsImportant))
{
document.getElementById('importantFlag').style.display = 'normal';
}
}
</script>

<img id="importantFlag" src="~/Images/important.png" style="display:none; height:100px; width:100px" />
@Html.Encode(Model.Title)<br />
@Html.Encode(Model.Author), @Html.Encode(Model.PublishDate)<br />
@Html.Encode(Model.Body) <br />
<br />
http://stackoverflow.com/questions/ask#

编辑:

页面如下所示

<script type="text/javascript">
function setImportantFlag()
{
if (false)
{
document.getElementById('importantFlag').style.display = 'normal';
}
}

setImportantFlag();
</script>

<img id="importantFlag" src="/Images/important.png" style="display:none; height:100px; width:100px" />
Big ol deibufouebwf<br />
, 01/01/0001 00:00:00<br />
<br />
<br /><script type="text/javascript">
function setImportantFlag()
{
if (true)
{
document.getElementById('importantFlag').style.display = 'normal';
}
}

setImportantFlag();
</script>

<img id="importantFlag" src="/Images/important.png" style="display:none; height:100px; width:100px" />
News article one<br />
Author One, 13/06/2016 21:49:04<br />
Well if it isn&amp;#39;t body one! <br />
<br />

最佳答案

我不知道你实际上在哪里调用你定义的函数。

尝试在声明后调用,如下所示:

<script type="text/javascript">
// Declare the function
function setImportantFlag(){
if (@Json.Encode(Model.IsImportant)){
document.getElementById('importantFlag').style.display = 'normal';
}
}
// Actually call the function
setImportantFlag();
</script>

更新

查看渲染的标记后,有一些原因可能导致此问题:

  • 重复 id 属性 - id 属性根据定义是唯一的,因此当您尝试使用 文档定位它时。 getElementById() 函数,它可能会导致一些奇怪的行为。
  • 重复函数定义 - 由于您还在分部 View 中创建函数,因此您将拥有多个相同的定义,这些定义将继续相互覆盖。

由于您所做的只是设置是否应隐藏某个元素,因此您可以考虑显式地不根据 bool 属性渲染该元素,您可以使用三元语句根据您的 Model 渲染适当的样式:

<!-- Use a class to avoid duplicate id attributes -->
<img class="importantFlag" src="~/Images/important.png" style="display:@(Model.IsImportant ? "normal" : "none"); height:100px; width:100px" />

如果元素很重要,这将处理显示该元素,否则隐藏它。它还可以避免重复 id 属性的任何问题,并完全删除任何 Javascript 函数。

关于Javascript 未在 MVC Razor View 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37821708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com