【问题标题】:Cannot trigger click on href(forcing href to clicked)无法触发点击href(强制点击href)
【发布时间】:2014-06-21 03:06:35
【问题描述】:

我刚刚制作了一个脚本,当我尝试在文档加载时自动单击 href 时,触发器没有发生。我希望已经自动单击了 href,但我没有触发。这是我的html

<li style="width: 25%; max-width: 320px; max-height: 200px;">
            <a href="#" class="linkProxy"><img src="index_files/small/shirt-4.jpg" data-largeimg="index_files/large/shirt-4.jpg" /></a>
            </li>

这是我的 Jquery

<script type="text/javascript">
$(document).ready(function(){
$('button.linkProxy').click(function(){
    location.href = $('#' + $(this).attr('rel')).attr('href');
});
});
</script>

你能帮我吗,因为我是 jquery 和 javascript 的初学者。在此先感谢,如果有的话,请建议任何其他方法。

【问题讨论】:

  • 你的网址是#?我看对了吗?
  • 除了设置一个事件处理程序之外,当文档加载时你也没有做任何事情。
  • 我认为您需要明确说明您想要做什么。a 元素上触发点击事件根本没有任何作用,因为它没有 @ 987654324@ 属性。
  • 这个问题不清楚,它可能意味着两件事中的一件。您要么想要处理按钮单击/href 单击,要么实际上希望它在页面加载时重定向。您有 2 个答案可以满足这两种情况。你认为你可以清理你的问题吗?

标签: javascript jquery html


【解决方案1】:
$('button.linkProxy')

将搜索类为linkProxy&lt;button&gt; 元素和 不会匹配任何元素,因为您的 html 中没有 &lt;button&gt;

您需要将&lt;a&gt; 标记为linkProxy 类,如下所示:

$(document).ready(function(){
 $('a.linkProxy').click(function(){
  location.href = $('#' + $(this).attr('rel')).attr('href');
 });
 $('a.linkProxy').trigger('click');
});

另请注意,您的 html 中没有 rel 属性,因为您没有对它进行解释,所以知道您想用它做什么......

【讨论】:

  • 我刚试过你的代码,它工作正常,我发现你的代码中的位置是未定义的,所以它被重定向到类似 /undefined
  • 你正在使用$(this).attr('rel'),它将尝试访问被点击的&lt;a&gt;标签的rel属性,而没有这样的属性......你能用你的内容更新问题吗?正在尝试做..
【解决方案2】:

听起来您想要重定向。 “自动点击”就是这样。

您可以尝试以下两种方法之一来模拟页面加载时的“自动点击”。

window.location.replace("http://stackoverflow.com");

window.location.href = "http://stackoverflow.com";

【讨论】:

    【解决方案3】:

    试试:

    <script type="text/javascript">
    $(document).ready(function(){
    $('button.linkProxy').click(function(){
    location.href = $('#' + $(this).attr('rel')).attr('href');
    });
    $('button.linkProxy').trigger('click');
    });
    </script>
    

    您刚刚在代码中定义了如何解释点击事件,您实际上并没有做出“点击”。

    【讨论】:

      猜你喜欢
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-21
      • 1970-01-01
      • 2018-02-27
      • 2019-02-22
      相关资源
      最近更新 更多