Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
709 views
in Technique[技术] by (71.8m points)

jquery assign onclick for li from a link

I have a list of items

<ul class="list">
    <li>
        <a href="#Course1" class="launch" onclick="alert('event 1')">event 1</a>
    </li>
    <li class="alt">
        <a href="#Course2" class="launch" onclick="alert('event 2')">event 2</a>
    </li>
    <li>
        <a href="#Course3" class="launch" onclick="alert('event 3')">event 3</a>
    </li>
    <li class="alt">
        <a href="#Course4" class="launch" onclick="alert('event 4')">event 4</a>
    </li>
</ul>

I want to be able to assign the onclick of the link to the onclick of the li aswell

My attempt so far is one click behind (as I am assigning the script to the onclick rather than executing the script)

$('.list li').click(function() {
    var launch = $('a.launch', this);
    if (launch.size() > 0) { this.onclick = launch.attr('onclick'); }
});

Thanks in advance Tim

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

building on @Thomas Stock's answer the following code prevents double execution on clicking on link instead of li. (got it from here jQuery site)

$(document).ready(function() {

    $('ul.list li').click(function(e) {
        var $target = $(e.target);
        if(!$target.is("li")) //magic happens here!!
        {
            return;
        }

        var launch = $('a.launch', this);
        if (launch.size() > 0) 
        { 
          eval(launch[0].onclick());
        }
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...