简体   繁体   English

点击href链接后显示div

[英]Show div after click on href link

I solve my first issue to show one or two div based on checkbox selection ( Show multiple div after click button only if checkbox are checked - thanks @J4k3z).我解决了我的第一个问题,即根据复选框选择显示一个或两个 div( 仅在选中复选框时才在单击按钮后显示多个 div - 感谢@J4k3z)。

My code is:我的代码是:


$div1 = $(".div1");
$div2 = $(".div2");

$div1.hide()
$div2.hide()

function showDiv(){
    if(document.getElementById('chk1').checked){    
        $div1.show()
    } else {
        $div1.hide()
    }
    if(document.getElementById('chk2').checked){
        $div2.show()
    } else {
        $div2.hide()
    }
}

<input type="checkbox" id="chk1" placeholder="Yes">
<label>Div 1</label>
<input type="checkbox" id="chk2" placeholder="Yes">
<label>Div 2</label>
<br />
<button onClick="showDiv()">Check!</button>
<br />
<div class="div1">Div no 1</div>
<div class="div2">Div no 2</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

This code run by button.此代码由按钮运行。 Is it possible to replace button with href link?是否可以用 href 链接替换按钮?

yes, for this you need to use an addEventListener() method.是的,为此您需要使用addEventListener()方法。

In your HTML, you have to make a link with an id在您的 HTML 中,您必须创建一个带有 id 的链接

<a id='link-id' href='#'>some link</a>

Then in javascript, add an event listener on this link然后在javascript中,在这个链接上添加一个事件监听器

$('#link-id').addEventListener('click', showDiv)

Another way you can try is using the .onclick() method(from here )您可以尝试的另一种方法是使用.onclick()方法(来自此处

$('#link-id').onclick = showDiv;

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

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