문제

What's the best way to combine two strings

String 1:

<a href="javascript:myFunc();" onclick="alert('myFunc executed')">Click here</a>

and String 2:

<a href="http://google.com">click here</a>

so that: myFunc() executed; alert appears; once alert is clicked, the page is being redirected to http://google.com

I'm asking about the most correct way to do that.

Thank you.

도움이 되었습니까?

해결책 3

Try this :

<a href="javascript:void(0)" onclick="alert('myFunc executed');myFunc();window.location='http://google.com'">Click here</a>

explanation :

javascript:void(0) Is for u to see a link.

다른 팁

Use:

<a href="http://google.com" onclick="myFunc(); alert('myFunc executed'); return true">click here</a>

Your approach is very "obtrusive" JavaScript. Nowadays, folks tend to recommend an Unobtrusive JavaScript approach.

<a id="myLink" href="http://google.com" data-message="myFunc executed">Click Here</a>

Note that there is no JavaScript in the HTML.

Then, in your script module, you can initialize as below (I use jQuery for brevity):

$("#myLink").click(function(){
    var href = $(this).attr("href"),
        message = $(this).attr("data-message");
    myFunc();
    alert(message);
    window.location.href = href;
});

This technique leaves your HTML clean and allows you to perform multiple actions on the click event.

Finally, if you are not familiar with the concept of modules in JavaScript, take a look at Douglas Crockford's book JavaScript, The Good Parts.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top