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