【问题标题】:javascript on click change href and open in new windowjavascript点击更改href并在新窗口中打开
【发布时间】:2012-05-08 08:01:24
【问题描述】:

我有一个 Django 项目,它为用户提供了将用户帐户与 Twitter 和 Facebook 等社交网络帐户相关联的可能性。这适用于 Django Social Auth,它基本上提供了一个标签来了解当前用户是否已经关联了帐户。它允许以下代码相应地显示 URL:

<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>

这是 Django 模板代码,执行时会给出以下 html(当然,显示的 hrefs 会根据用户的个人资料而变化,如果帐户与社交网络相关联,这里我会同时显示连接(对于Facebook)和断开(对于 Twitter)URL):

<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>

这工作正常,但有各种缺点。首先,单击时,链接将通过打开关联/断开页面失去当前导航。这可以通过不打开它们来解决,如果存在的话,只需用 javascript 调用 GET(我记得用 javascript 调用 POST 来发送一些数据,GET 也必须是可能的?)。然后另一个缺点是点击时链接不会自动更新,必须重新加载页面。这可以通过更改 href 来解决,如果它是 'associate' 则显示 'disconnect',如果它是 'disconnect' 则显示 'associate' 并切换 URL。

【问题讨论】:

  • 对不起,我无法完全理解您的要求。用target="_blank" 标记您的链接以实现您想要的有什么问题?为什么需要 AJAX?
  • 用target="_blank"标记没问题,好主意。

标签: javascript jquery django django-socialauth


【解决方案1】:

不是最好的方法……

……但速度很快(使用 jQuery)。您应该能够通过创建相应的 ajax 视图来改进它。

(未经测试的代码,但提供一个想法)

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

【讨论】:

  • 我知道这会加载 URL,但我也想更改 href 的文本;每次单击时,URL 应从登录更改为断开连接,并从断开连接更改为登录。相应的文字也应该改变。
  • 这实际上应该从给定的href加载url,然后用加载页面中的这一部分替换“#social_associations”的内容。所以这也应该更新链接。实际上它的作用与没有 javascript 的情况相同 - 但它并没有将页面完全加载到浏览器窗口中,只是这一部分。
猜你喜欢
  • 2014-04-08
  • 1970-01-01
  • 2018-03-03
  • 2019-10-20
  • 2012-11-26
  • 1970-01-01
  • 2018-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多