Get a reference to the anchor element of an Ajax.A

2019-02-25 07:37发布

Basically my question is similar or even a duplicate of this one, except that I'm using MVC Razor. And I'm certain that the answers there are outdated since the client library currently used is jQuery / unobtrusive ajax.

So to sum up the question, I'm trying to access the anchor element that triggered the Ajax request in the handler specified at the OnSuccess property of the provided AjaxOptions.

Here is the 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; });
}

1条回答
Rolldiameter
2楼-- · 2019-02-25 08:08

here is a link to an answer that shows several solutions and a good mark explanation of the issue.

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

you could always just write

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

You can then access the clickedLink variable in the success handler (remember to declare it with page scope).

EDIT:

After some playing around with the call stack, you could try something like this:

<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"})

Not sure I would trust this in production though. I'd do something more like:

<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);"})
查看更多
登录 后发表回答