【问题标题】:href does not work on anchorhref 在锚点上不起作用
【发布时间】:2018-06-30 05:37:21
【问题描述】:

我有以下一段 javascript。它使用 Ajax 从 API 中获取报价。报价显示在报价 div 中,但 href 未在 twitterAnchor 处刷新。

    jQuery('#button').on('click', function(){
            
        jQuery.ajax({
        url: "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&  filter[posts_per_page]=1&_jsonp=mycallback",
        type: 'GET',
        dataType: "jsonp",
        success: function(json){
            document.getElementById('quote').innerHTML = json[0].content;
            document.getElementById('twitterAnchor').href =  "https://twitter.com/intent/tweet?text=" + json[0].content;    
            }
        });
    });
<!-- Here is the anchor. -->

      <div id="tweet">
          <a id ="twitterAnchor" href="" class="twitter-share-button" target="_blank" >Tweet</a>  
      </div>

当我单击 twitterAnchor 时,页面会刷新。控制台什么也没显示,有人知道发生了什么吗?

【问题讨论】:

    标签: javascript ajax jsonp anchor


    【解决方案1】:

    经过一天的尝试找出错误...这就是解决方案:

    jQuery('#button').on('click', function(){
    
        jQuery.ajax({
        url: "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=mycallback",
        type: 'GET',
        dataType: "jsonp",
        success: function(json){
            document.getElementById('quote').innerHTML = json[0].content; 
            }
        });
    });
    
    jQuery('#twitterAnchor').on('click', function () {
        jQuery(this).attr("href","https://twitter.com/intent/tweet?text=" + document.getElementById('quote').innerHTML);
    });
    

    问题是:如果您尝试更改 ajax 连接中的 href,它不起作用。我真的不知道为什么,我真的很高兴知道。

    【讨论】:

      【解决方案2】:

      不要为 href 分配新值,而是使用 jQuery attr 方法。

      $('#twitterAnchor').attr('href', 'https://twitter.com/intent/tweet?text=' + json[0].content);
      

      【讨论】:

      • 是的,伙计,我正在使用它,但在我的 ajax 连接之外。它在里面不起作用。我的答案如下。
      • 你没有在原来的答案中使用它就是我的意思。
      【解决方案3】:

      您选择的 id 是 button,而不是 twitterAnchor。所以试试jQuery('#twitterAnchor')

      其次,您需要防止单击锚点时浏览器的默认行为:

      jQuery('#twitterAnchor').on('click', function (e) {
        e.preventDefault();
        jQuery.ajax({
          url: "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&  filter[posts_per_page]=1&_jsonp=mycallback",
          type: 'GET',
          dataType: "jsonp",
          success: function (json) {
            document.getElementById('quote').innerHTML = json[0].content;
            jQuery(this).attr("href","https://twitter.com/intent/tweet?text=" + json[0].content);
          }
        });
      });
      

      【讨论】:

      • 我不明白,我在选择主播 ID。
      • 我只想刷新twitterAnchor上的href
      • 编辑了我的答案
      • 感谢您的回复@Abderrahmane TAHRI JOUTI,但我猜我选择的部分是正确的。我想要做的是在加载一些新报价时刷新锚上的 href。
      • 更新了我的答案,抱歉我之前没有正确阅读。
      猜你喜欢
      • 2010-11-10
      • 1970-01-01
      • 2013-02-22
      • 2016-02-26
      • 1970-01-01
      • 2021-05-01
      • 2016-06-27
      • 1970-01-01
      • 2011-03-02
      相关资源
      最近更新 更多