简体   繁体   English

仅<a>在带有div的div中</a>选择

[英]Select only <a> inside div with js

How do I select the 1st a in this code with JavaScript? 如何使用JavaScript在此代码中选择1st a? (href=some.php) (href = some.php)

<div class="accordionButton"><div id="acr_btn_title"><a href="some.php"><p>stuff</p></a></div><div class="hn_little_box"></div></div>
            <div class="accordionContent" >
                <ul>
                    <li><a href="page_01">Page 01</a></li>
                    <li><a href="page_02">Page 02</a></li>
                    <li><a href="page_03">Page 03</a></li>
                </ul>
        </div>

I want to make it so when that <a> is clicked, the JavaScript doesn't execute. <a> ,以便在单击<a>时不执行JavaScript。 This is for an accordion side nav, so when it's clicked the accordion doesn't expand, but still tells the browser to go to that page. 这是针对手风琴侧导航的,因此单击时手风琴不会展开,但仍会告诉浏览器转到该页面。

I'm thinking something like this: 我在想这样的事情:

 <script type="text/javascript">
  $('#acr_btn_title a').click(function() {
      return false;
  });
  </script>

but this stops the link from working. 但这会停止链接的工作。 I just want the JavaScript to stop, not stop the <a> from functioning! 我只是想停止JavaScript,而不是停止<a>的功能!

在此处输入图片说明

You're very close, but if you only want the first one, use the :first selector: 您非常接近,但是如果只想要第一个,请使用:first选择器:

$('#acr_btn_title a:first').click(function() { 
    return false; 
});

I'd suggest you use preventDefault() and stopPropagation() instead of return false , though: 我建议您使用preventDefault()stopPropagation()而不要return false

$('#acr_btn_title a:first').click(function(e) { 
    e.preventDefault();
    e.stopPropagation();
});

Do take note that you cannot make sure that a javascript is called when clicking a link. 请注意,您无法确保在单击链接时无法调用JavaScript。 What you can do though, is add the link logic to the click event, but prevent the default: 但是,您可以做的是将链接逻辑添加到click事件中,但是要避免使用默认值:

$('#acr_btn_title a:first').click(function(e) { 
    e.preventDefault();
    e.stopPropagation();

    //Your javascript goes here

    location.href = $(this).prop('href');
});

You can also place the accordion logic (if you control it) on anything but the first one using gt() : 您也可以将手风琴逻辑(如果你控制它)上的任何东西,但使用的第一个gt()

$('#acr_btn_title a:gt(0)').accordionPlugin();

or refer to a elements with the href attribute not set to eg. 或使用href属性设置为例如a元素进行引用。 # : #

$('#acr_btn_title a[href!=#]').accordionPlugin();

由于您使用的是jQuery,请尝试$($("#acr_btn_title a")[0])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM