简体   繁体   English

从 html.actionlink 在外部页面上调用 jQuery 函数

[英]Calling jQuery function on external page from html.actionlink

I have an action link like this:我有一个这样的操作链接:

@html.actionlink("link", "action", "controller", new { id = item.id }

I want this link to call a jQuery function on an external page.我希望此链接在外部页面上调用 jQuery 函数。 I have tried with onclick but it always goes to the default controller action method and so does for @class .我尝试过onclick但它总是转到默认的控制器操作方法, @class也是如此。

I would like to know can I use it like this:我想知道我可以这样使用它:

@html.actionlink("link text", null, null, new { id = item.id }, new { onclick = "myfunction() }

This still does not call the jQuery function, what am I doing wrong?这仍然没有调用jQuery函数,我做错了什么?

here is my html hyperlink这是我的 html 超链接

@item.ProductID.ToString() @item.ProductID.ToString()

and below is my jquery script locate in an external js file下面是我的 jquery 脚本位于外部 js 文件中

$(document).ready({
function showdetails(id)
{
alert("you clicked me")
});

If you just want to make it run a jQuery function and not go to a controller then there's no point using the actionLink helper - the whole purpose of that is to generate a hyperlink with the correct URL to the action method.如果你只是想让它运行一个 jQuery 函数而不是去控制器,那么使用 actionLink 助手是没有意义的 - 整个目的是生成一个带有正确 URL 的超链接到 action 方法。 Instead, just write a HTML link (or button) directly and attach the click event to it.相反,只需直接编写一个 HTML 链接(或按钮)并将点击事件附加到它。 There's no need to us any Razor code.我们不需要任何 Razor 代码。

Something like this:像这样的东西:

<button type="button" class="linkbutton" onclick="myfunction(@item.id)">Click here</button>

The other mistake is to put the function within a $(document).ready({ block. It's unnecessary because the idea of that block is only to stop code executing before the page has finished loading. With a function, which is only called from other code, not executed immediately, you don't have that worry. And it causes the error because it means that your function only has scope within that block. It isn't accessible to code outside the block.另一个错误是将函数放在$(document).ready({块中。这是不必要的,因为该块的想法只是在页面加载完成之前停止代码执行。使用一个函数,它只能从其他代码,没有立即执行,您不必担心。它会导致错误,因为这意味着您的函数仅在该块内具有作用域。块外的代码无法访问它。

Demo:演示:

 function myfunction(x) { alert(x); }
 .linkbutton { border: none; background: none; color: blue; text-decoration:underline; } .linkbutton:hover { cursor:pointer; }
 <button type="button" class="linkbutton" onclick="myfunction(3)">Click here</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM