我有一些具有公共类名的超链接。这个超链接是在我的网页上用mvc asp.net助手动态创建的。 现在我想编写一个脚本来确定点击的特定链接,并在单击此链接时执行javascript函数。 我的代码如下。
我的mvc代码生成链接,请注意传递的函数updateWaitingState(this)
td> @AntiXss.HtmlEncode(customerchatname) @Html.ActionLink("chat", "StartChat", new { threadid = avisitor.ThreadID, email = AntiXss.HtmlAttributeEncode(email) }, htmlAttributes: new { target = "_blank", @class = "chat", operatorid = avisitor.OperatorID, connectionid = AntiXss.HtmlAttributeEncode(connectionid), threadid = avisitor.ThreadID, onClick = "updateWaitingState(this);" })</td>
此链接的我的javascript函数如下所示,JQuery已在链接上方调用。
<script type='text/javascript'>
function updateWaitingState(sender) {
var parentid = $(sender).attr("data-parentid");
alert(parentid);
}
</script>
问题是浏览器为发件人对象生成了未定义的内容。我已经尝试了几个小时的调试,我似乎无法找到问题。
当我在浏览器中运行我的代码时。 html看起来像这样
<tr id="kayode@yahoo.com">
<td> kayode <a class="chat" connectionid="135976e6-799b-4cda-a764-a00f7110d515" href="/Visitor/StartChat?threadid=3&email=kayode%40yahoo.com" onclick="updateWaitingState(this);" operatorid="1" target="_blank" threadid="3">chat</a></td>
<td>271.0.0.1</td>
<td>Waiting</td>
<td></td>
<td>9/13/2014</td>
<td>04:15:18</td>
<td>00:00:10</td>
<td>271.0.0.1</td>
</tr>
答案 0 :(得分:0)
为anchor
代码添加唯一id
代'a1'
并尝试此操作:
document.getElementById('a1').addEventListener('click', function(e){
e.preventDefault();
alert($(this).data('parentid'));
});
编辑: - 如果您想在课堂上添加事件监听器,请执行以下操作:
document.querySelector('[class=chat]').addEventListener('click', function(e){
e.preventDefault();
alert($(this).data('parentid'));
});
或尝试Pure Jquery方法: -
$("a[class='chat']").click(function(e){
e.preventDefault();
alert($(this).data('parentid'));
});
并确保您的锚标记中有attribute
,即data-parentid
。
答案 1 :(得分:0)
sender
未定义,parentid
,因为您的操作链接的html没有data-parentid
属性。将html修改为
@Html.ActionLink(..., htmlAttributes: new { ... data-parentid="SomeValue", onClick = "updateWaitingState(this);" })
答案 2 :(得分:0)
我必须更正我生成的这个HTML。问题不是来自javascript而是来自html。
<a href="@Url.Action("StartChat", new { threadid = avisitor.ThreadID, email = AntiXss.HtmlAttributeEncode(email) })" class="chat" target="_blank" data-parentid="@AntiXss.HtmlAttributeEncode(email)" onclick="updateWaitingState(this);">chat</a>
这解决了这个问题。非常感谢您的所有贡献。我真的很感激!!!!。