开发者

How to properly use href="#someID"?

开发者 https://www.devze.com 2023-04-03 02:47 出处:网络
Basically, I want to have a list of links, where each link will show a div. I have everything set up so that this works, but I just have no idea as to which events are getting fired, and in what order

Basically, I want to have a list of links, where each link will show a div. I have everything set up so that this works, but I just have no idea as to which events are getting fired, and in what order. I want to add functionality so that when one of these divs is shown, javascript is run. But so far using code such as this:

<a href="#div1" onclick="some_script()" />

calls the some_script() before it actually shows the div. Which is useless to me, since I am trying to get a certain input box to be focused, after showing the div.

Can anyone tell me which jquery events get fired, or and jquery events开发者_JAVA技巧 that I can use so that I can run some_script() after the div is shown to the user?


You can use something like this

$(document).ready(function(){
    $('a').click(function(){ //attaches click event to all 'a' elements on page
        var div = $(this).attr("href").substr(1); //gets the div
        $(div).show(); //show the div
    });
});

This link should get you started with jQuery. http://docs.jquery.com/Main_Page


If I understood your requirements correctly:

HTML

<p><a href="#div_one" class="trigger">1st div</a></p>
<p><a href="#div_two" class="trigger">2nd div</a></p>
<div id="div_one">
    Some content
    <input type="text" name="input1" class="input">
</div>
<div id="div_two">
    Some more content
     <input type="text" name="input2" class="input">
</div>

CSS

div {
    border: 2px solid green;
    background-color: lightgreen;
    color: black;
    display: none;
    margin: 10px;
    padding: 5px;
}

JavaScript

$('.trigger').click(function(e) {
    e.preventDefault();
    var target_div = $(this).attr('href');
    $(target_div).toggle();
    $(target_div).find('.input').focus();
});

jsFiddle demo: http://jsfiddle.net/byuPL/

0

精彩评论

暂无评论...
验证码 换一张
取 消