2014-04-04 46 views
0

我有这样的代码在.cshtml文件传递参数:通过在HTML文件.cshtml

var peopleList = $('#PeopleListTable').dataTable({ 
        // not relevant 
        "fnRender": function (oObj) { 
         var documentiddata = oObj.aData[0]; 
         var notesdata = (oObj.aData[2]); 
         //alert(notesdata); 

         if (notesdata != null) { 
          var image = "images/AR/Check-on.png";               
          // return '<a href="#" id="' + notesdata + '" onclick="return ShowNotes(this);">' + '<img src="' + image + '" />' + '</a>'; 
          return '<p><a onmouseout="return hideNotePopup();" onmouseover="return showNotePopup(notesdata, event);" href="javascript:void(0);" id="' + documentiddata + '">' + '<img src="' + image + '" />' + '</a></p>' 
         } else { 
          return '<a href="#" id="' + documentiddata + '"> ' + '<img src="images/AR/Check-off.png" />' + '</a>'; 
         }       
        } 
        }, 
       { "sName": "OfficerName", sType: "string", sWidth: "12%" }, 
       { "sName": "CreateDate", sType: "string", sWidth: "15%" }, 
       { "sName": "FinalizedDate", sType: "string", sWidth: "15%" }, 
       { "sName": "TransferDate", sType: "string", sWidth: "15%" }, 
       { "sName": "AgencyOri", sType: "string", sWidth: "10%" } 
      ] 
     }); 

那么这个代码在JavaScript:

function showNotePopup(notesdata, e) { 
     $("#NoteDialog").dialog('close'); 
     $("#NoteDialog").removeClass("ui-icon ui-icon-closethick"); 
     $("#NoteDialog").dialog({ 
      autoOpen: false, 
      modal: true, 
      resizable: false, 
      position: [e.pageX, e.pageY-190] 
     }); 
     $("#NoteDialog").dialog('open'); 
     document.getElementById("note").innerHTML = notesdata; 
    } 

这段代码的目标是将鼠标悬停在数据表中的注释图像,然后弹出显示注释的内容。如果我有alert(notesdata),说明正确显示。但是,当我将鼠标悬停在图像上并检查控制台时,它说在showNotePopup()调用中未定义notesdata。我试图通过thisoObj,无济于事。我怎样才能从cshtml里面获得notesdata到javascript的功能?

回答

3

变量notesdata只存在于函数fnRender的上下文中。事件onmouseover在不同的上下文中执行,所以变量超出范围。您需要通过

onmouseover="return showNotePopup(&quot;' + notesdata + '&quot;, event);" 
+0

+1改变

onmouseover="return showNotePopup(notesdata, event);" 

。请注意,所有形式的'eval'通常被认为是不好的做法...不幸的是,OP是用字符串连接构造html而不是使用一些模板引擎或者使用jQuery创建元素 - 所以这个答案(如果'notesdata'来减去脚本注入问题从用户)是好的方法。 –

+0

@ClaudioRedi这是造成语法错误,而以前没有一个。开发工具告诉我有一个意外的令牌}。任何可能的原因?另外,我在你的答案中交换了单引号和双引号的顺序,因为整个return语句用单引号引起来。 – aquemini

+0

@aquemini:对不起,我引用了一个错误。请尝试用编辑的版本 –