在onSuccess处理得到的Ajax.ActionLink的锚元素的引用(Get a refere

2019-09-02 08:29发布

基本上我的问题是相似的或甚至重复这一个,但我使用MVC剃刀。 我敢肯定的答案有过时的,因为目前使用的客户端库的jQuery / AJAX不显眼。

因此,要总结的问题,我想访问引发了在指定的处理Ajax请求的锚元素OnSuccess所提供的财产AjaxOptions

这里是ActionLink

@Ajax.ActionLink("Add opening times entry", "AddOpeningTimes", 
  new { htmlPrefix = Html.HtmlPrefixFor(m => Model.OpeningTimes) },
  new AjaxOptions { UpdateTargetId = "openingTimes",
    InsertionMode =  nsertionMode.InsertAfter,
    OnSuccess = "updateHtmlPrefix" },
  new { title = "Add opening times entry" })

JS:

function updateHtmlPrefix() {
  this.href = this.href.replace(/\d(?=]$)/, function (i) { return ++i; });
}

Answer 1:

这里是显示几种解决方案和问题的一个好成绩,解释答案的链接。

https://stackoverflow.com/a/1068946/1563373

你总是可以只写

 OnBegin="function() { clickedLink = $(this); }" 

然后,您可以访问成功处理程序(记得页面范围申报吧)clickedLink变量。

编辑:

经过一番玩弄调用堆栈,你可以尝试这样的事:

<script type="text/javascript">    
    function start(xhr) {        
        var stack = start.caller;
        // walk the stack
        do {
            stack = stack.caller;            
        } while (stack.arguments != undefined && stack.arguments.length > 0 && (stack.arguments[0].tagName == undefined || stack.arguments[0].tagName != "A"))
    //stack now points to the entry point into unobtrusive.ajax
    if (stack.arguments != undefined)
        xhr.originalElement = $(stack.arguments[0]);

    //blech        
}

function UpdateHrefText(result, status, xhr) {
    debugger;
    if(xhr.originalElement != undefined)
        xhr.originalElement.text(result.Message);
}
</script>


@Ajax.ActionLink("Test", "Message", "Home", new AjaxOptions{ OnBegin = "start", OnSuccess = "UpdateHrefText"})

不知道我会在生产,虽然相信这个。 我会做更多的东西一样:

<script type="text/javascript">
var theLink;

function start(xhr) {
    xhr.originalElement = theLink;        
}

function UpdateHrefText(result, status, xhr) {
    debugger;
    if(xhr.originalElement != undefined)
        xhr.originalElement.text(result.Message);
}
</script>


@Ajax.ActionLink("Test", "Message", "Home", null, new AjaxOptions{ OnBegin = "start", OnSuccess = "UpdateHrefText"}, new { onclick="theLink = $(this);"})


文章来源: Get a reference to the anchor element of an Ajax.ActionLink at the OnSuccess handler