How to format a URL.Action() call in JQuery to set a link's href attribute?

旧街凉风 提交于 2020-01-04 06:44:18

问题


I need to set the href attribute of a link to point to a specific image, which has its id from the database set as its title. However, I am having trouble with trying to format the string to include a call to get the title attribute of the image.

Here is the base string:

$("#favoriteLink").hover(function() {
    $(this).attr("href", '<%: Url.Action("FavoriteWallpaper", "Wallpaper", new{wallpaperId='+$(this).children.attr("title")+'}) %>');
});

favoriteLink is a div and the child is just one image.


回答1:


Oh no, you can't mix server side code and javascript as you are trying to. How about this:

$('#favoriteLink').hover(function() {
    var title = $(this).children.attr('title');
    $(this).attr('href', function() {
        var url = '<%= Url.Action("FavoriteWallpaper", "Wallpaper", new { wallpaperId= "_TITLE_TO_REPLACE_"}) %>';
        return this.href.replace('_TITLE_TO_REPLACE_', title);
    });
});



回答2:


You're URL.Action is rendered serverside and your javascript client-side. You wont have access to dom elements when you're trying to build the link.

You should get the actual URL thats rendered in URL.Action and build the string client-side



来源:https://stackoverflow.com/questions/6364270/how-to-format-a-url-action-call-in-jquery-to-set-a-links-href-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!