javascript on click change href and open in new window

蓝咒 提交于 2019-12-11 16:48:47

问题


I have a Django project that offers its users the possibility to associate a user account to some social networks accounts like Twitter and Facebook. This works with Django Social Auth which basically provides a tag to know if the current user has already associated accounts or not. It allows the following code to display URLs accordingly:

<fieldset id="social_associations" class="">
    <legend>Social Associations</legend>

{% for key, value in social_auth.items %}
    <img src="/static/img/{{ key }}_icon.png" alt="{{ key }}" width="25" height="25" />
    {% if value %}
        <a href="/social/disconnect/{{ key }}">Disconnect from {{ key }}</a>
    {% else %}
        <a href="/social/login/{{ key }}">Associate your account to {{ key }}</a>
    {% endif %}
    <br />
{% endfor %}
</fieldset>

This is Django template code, when executed it will give the following html (of course the displayed hrefs change based on the user's profile, if the account is associated or not with the social network, here I display both the connect (for Facebook) and disconnect (for Twitter) URLs):

<fieldset id="social_associations" class="">
<legend>Social Associations</legend>
<img width="25" height="25" alt="twitter" src="/static/img/twitter_icon.png">
<a href="/social/disconnect/twitter">Disconnect from twitter</a>
<br>
<img width="25" height="25" alt="facebook" src="/static/img/facebook_icon.png">
<a href="/social/login/facebook">Associate your account to facebook</a>
<br>
</fieldset>

This is working ok but there are various drawbacks. First when clicked, the links will lose current navigation by opening the associate / disconnect pages. That could be solved by not opening them, just calling a GET with javascript if that exists (I remembering calling POST with javascript to send some data, GET must be possible too?). Then another drawback is that when clicked the links do not update automatically, the page must be reloaded. This could be solved by changing the href to show 'disconnect' if it was 'associate' and 'associate' if it was 'disconnect' and switching the URL as well.


回答1:


Not the nicest way…

… but a fast one (using jQuery). You should be able to improve it whit creating eg corresponding ajax views.

(untested code, but to give an idea)

$('a', '#social_associations').live('click', function(e){
    e.preventDefault();
    $('#social_associations').load($(this).attr('href') + ' #social_associations');
});


来源:https://stackoverflow.com/questions/10494835/javascript-on-click-change-href-and-open-in-new-window

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