在Javascript中的更多Razor中使用的Razor变量



我循环遍历多个项目并为每个项目设置如下所示的图像标签。每个事件都有一个 onmouseover 和 onmouseout 事件。数据库存储鼠标悬停和鼠标退出图像目录,用分号分隔。此部分运行良好。

<img onmouseover="hover(this, @id);" onmouseout="unhover(this, @id);" src="@(tblIconTable.getSpecificIconFromId(id).icon.Split(';')[0])" />

问题是当我到达我的 javascript 事件时

function hover(element, Id) {
    element.setAttribute('src', '@(tblIconTable.getSpecificIconFromId(Id).icon.Split(';')[1])');
}
function unhover(element, Id) {
    element.setAttribute('src', '@(tblIconTable.getSpecificIconFromId(Id).icon.Split(';')[0])');
}

我在javascript中的更多剃刀中使用的"Id"无法识别。有没有一个聪明的解决方法?

一种方法是将两个 url 作为数据属性分配给每个 img 标签,然后在悬停/取消悬停函数中读取这些属性:

<img onmouseover='hover(this)' onmouseout='unhover(this)' data-img-hover='@(tblIconTable.getSpecificIconFromId(Id).icon.Split(';')[1])' data-img-unhover='@(tblIconTable.getSpecificIconFromId(Id).icon.Split(';')[0])' src='@(tblIconTable.getSpecificIconFromId(Id).icon.Split(';')[0])'>
function hover(element) {
    element.setAttribute('src', element.data('img-hover'));
}
function unhover(element) {
    element.setAttribute('src', element.data('img-unhover'));
}

最新更新