0

我的问题和这个一样

我也遇到了同样的问题,href事件'clicked'没有触发。然后我更改为altand element is span。这是我的代码

<li><h2><span id='aa' alt="#inbox"><span>Inbox</span></span></h2></li>  

这条线是我的第二个孩子 ul。我想在页面加载时触发/单击此行。

但我想知道如何触发这个跨度的(#aa)点击事件。尝试了以下代码。但没有奏效。
第一次尝试:

var href = $('#aa').attr('alt');
      window.location.href =href; // this gave me 404 error   

第二次尝试:

 $('#aa').trigger("click")   // this has no change

当点击上述 li>span 时,将执行编辑功能。我希望页面加载后自动单击 li 的跨度。这个问题的答案在使用时说明了一些问题<a href>。因此,我使用了span标签。我使用 jQuery 1.6

4

4 回答 4

3

Your first try gave you a 404 because you tried to change the URL to just #inbox. I'm assuming you actually wanted to append the hash to your current URL, in which case you can use the location.hash property:

window.location.hash = href;

I think you may also want to use an a element instead of a span, since then it will have this behaviour by default and you won't have to bind click events to handle it.

于 2012-04-19T12:25:46.577 回答
1

Edit : one more thing you are pointing to url which is works for A tag not for Span tag, Jquery how to trigger click event on href element this is for A tag which you mention in your question.

there is on issue if you are triggring the click event than you should bind click event with the span than use trigger function to trigger it

Write click event

$('#aa').click( function() 
    {
             alert('span clicked');
   });

Trigger event than

$('#aa').trigger("click");
于 2012-04-19T12:25:09.667 回答
1

我认为最简单的解决方案是将跨度更改为锚标记以处理加载后的任何点击,如果您只想将哈希标记添加到当前 url。然后你可以有一点 jquery 来选择你想要的页面加载链接。

<!doctype html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript">
    $(function() {
        window.location.hash = $('#second').attr('href');
    });
    </script>
</head>
<body>
    <ul>
        <li><a href="#first">First</a></li>
        <li><a href="#second" id="second">Second</a></li>
    </ul>
</body>
</html>

如果这不是您想要的,并且您想在点击时运行更多代码,那么您可以将点击逻辑分离到一个函数中并在页面加载时调用它,如下所示:

<!doctype html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript">
    $(function() {
        //your function that does stuff on click
        function doStuff(item) {
            window.location.hash = $(item).attr('href');
            //cancel the click
            return false;
        }

        //call the function on page load
        doStuff($('#second'));

        //call the function on click
        $('#nav a').click(function() { doStuff(this); });
    });
    </script>
</head>
<body>
    <ul id="nav">
        <li><a href="#first">First</a></li>
        <li><a href="#second" id="second">Second</a></li>
    </ul>
</body>
</html>
于 2012-04-19T15:24:44.620 回答
1

如果我理解正确,这将解决您的问题;

像这样给可点击的属性跨越。

$('#aa')
        .bind('click', function () { 
               .....
});

并在 document.ready 中这样称呼它

$('#Control_2').click();
于 2012-04-19T12:53:11.430 回答