如何在 <a> 标签内创建可点击按钮或 link 并且仍然可以右键点击?

How do I create a clickable button or link inside an <a> tag and still be right-clickable?

您好,我目前正在制作一个通知下拉菜单,每个 <li> 都包含一个 link 或一个 <a> 标签。

我想制作类似 facebook 的东西 notification。

现在的问题是我想在 <a> 标签内放置一个小按钮或可点击的元素。或者只是 我想在 <a> 标签 中嵌套 <a>。 在 google 上搜索了一些答案后,我发现不可能仅使用 HTML 来嵌套它。

有人建议将 <a> 放在 <div> 中,并使用 onclick 事件。 但它不会像 this.

那样使 link 可右键单击

那么如何制作一个可右击的 link 并且在里面,它有一个可点击的按钮或一个 link?

谢谢。

编辑: 经过几次搜索,到目前为止,我已经找到了这段代码。

HTML:

<li class="dropdown">
    <a href="javascript:void(0)" class="dropdown-toggle" data-toggle="dropdown" role="button">Notification</a>
    <ul class="dropdown-menu">
        <li>
            <div class="notif-box">
                <a href='#' onclick='testfunction();' style="font-size: 50; float: right; text-decoration: none;">X</a>
                <a href="index.php" id='notif-link-body'></a>
                <b>Notification title here</b>
                <p>Content body here</p>
            </div>    
            </a>
        </li>
    </ul>
</li>

JS

$(".notif-box").click(function() {
    var x = $("#notif-link-body").attr("href");
    window.location = x; 
    return false;
});

function testfunction(){
    alert("It works!");
    return false;
}

CSS

.notif-box {
    width: 250px;
    cursor: pointer;
    display: block;
    padding: 3px 20px;
    clear: both;
    font-weight: normal;
    line-height: 1.42857143;
    color: #333;
    white-space: nowrap;
}

.notif-box:hover,
.notif-box:focus {
    color: #262626 !important;
    text-decoration: none !important;
    background-color: #f5f5f5 !important;
}

唯一的问题是每当我点击 "x" 按钮时,它仍然会在弹出警报后将我重定向到 index.php

如果您使用的是Bootstrap,您尝试过吗:

<div class="dropdown">
  <a id="dLabel" data-target="#" href="http://example.com" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
    Dropdown trigger
    <span class="caret"></span>
  </a>

  <ul class="dropdown-menu" aria-labelledby="dLabel">
    ...
  </ul>
</div>

引用自:http://getbootstrap.com/javascript/#dropdowns

我终于自己弄明白了。 我做了这样的结构...

<a href="index.php" style="display: block;">//Parent link
 <span class="x-button" style="align: right;">X</span>//The button inside the parent link
 Some text here...
</a>

我所做的是将 <a> 作为父元素 这样用户仍然可以 右键单击​​ 并做一些事情喜欢 打开 link 作为新标签页

因此,为了防止浏览器在用户单击子元素时触发父元素,我使用 jquery hover() and bind() 禁用父元素 link child 悬停,并在鼠标离开时重新启用它。

$(".x-button").hover(function(){//On mouse enter
    var parent = $(this).closest('a');
    parent.bind('click', false);//Disable the parent
}, function(){//On mouse leave
    var parent = $(this).closest('a');
    parent.unbind('click', false);//Re-enable the parent
    parent.blur();//Unfocus the element
});

$(".x-button").click(function() {
    //Do something on click
});