Submit button in a hyperlink
I would have never thought that it was valid markup to put a <input type="submit" />
in an anchor <a>
like so:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Submit input in a hyperlink</title>
</head>
<body>
<form action="/form-submission" method="get">
<a href="/hyperlink-click"><input type="submit" /></开发者_开发技巧a>
</form>
</body>
</html>
Oddly enough though, if you feed this into the w3c validator, it validates.
What is supposed to happen when a user clicks on the submit button? Would this kind of setup just be unpredictable with different browsers doing whatever they please, or are there explicit rules dictating expected behavior? Would doing something like this ever come in handy?
The behaviour isn't consistent between browsers.
Milimetric answer may be good for javascript, but consider what happens with unscripted html.
See the js fiddle http://jsfiddle.net/PjtPZ/
Here I've just changed the html of the question so that the link navigates the page to www.microsoft.com and the form submits to www.google.com.
Click on the button in Firefox 4.0, IE9 or Opera 11 and the Google page is the one that appears. Do it in Chrome 10.0 or Safari 4.0 and you get the Microsoft page.
This is probably why it is disallowed in HTML5.
So here's the answer :) It may not validate in HTML5, it may validate in HTML < 5, but I was still curious to see what happened. It turns out it's pretty logical. The button event fires first and then bubbles up to the link event. Then the link event fires. You can play with it here:
http://jsfiddle.net/yEUM2/
It does the same thing in IE8, FF4, Chrome 10
In short, it isn't valid HTML. It probably shouldn't be valid and, as Richard points out, it's interesting it's been addressed in HTML5
Try running the same code as HTML5. The HTML5 definition has corrected this by giving the error:
The element input must not appear as a descendant of the a element.
This is because you are displaying two buttons on the same place, so which button action should take preference? Essentially you're hiding one button action from the user, which is as good as having no second button at all.
There's more information on this in HTML: The Markup Language Reference
精彩评论