Reading form action property in IE6, if form has a field named “action”

别来无恙 提交于 2019-12-07 13:01:03

问题


Given the form below:

<form id="myForm" action="index.php">
    <input type="hidden" name="action" value="list" />
    <input type="submit" />
</form>

How can I get the value for the action property of the form (index.php) using IE6?

Hint: I have tried

document.getElementById('myForm').action

and

document.getElementById('myForm').getAttribute('action')

But neither of them work. They both return the input field (document.getElementById('myForm').action.value == 'list').


回答1:


There is a simple way, using the node's attributes collection:

document.getElementById("myForm").attributes["action"].value

Test page to try it out (also demonstrates the brokenness of getAttribute as mentioned David Dorward's answer):

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>Form Action Access</title>
<script type="text/javascript">
function dotAccess()
{
    alert(document.getElementById("myForm").action.value);
}
function getAttributeAccess()
{
    alert(document.getElementById("myForm").getAttribute("action"));
}
function attributesAccess()
{
    alert(document.getElementById("myForm").attributes["action"].value);
}
</script>
</head>
<body>
<form id="myForm" action="foo">
  <input type="hidden" name="action" value="bar">
  <input type="button" onclick="dotAccess()" value="form.action">
  <input type="button" onclick="getAttributeAccess()" value='form.getAttribute("action")'>
  <input type="button" onclick="attributesAccess()" value='form.attributes["action"]'>
</form>
</body>
</html>



回答2:


David's right. Here's a less nasty way than the regex though:

var action= document.forms.myForm.cloneNode(false).action;

(Because the clone is shallow, there is no ‘input name="action"’ inside the new form element to confuse it.)




回答3:


There isn't a simple way.

The presence of the action field, clobbers the action property of the form and getAttribute is broken in IE < 8.

The only way I can think of is to get dirty with regular expressions. I would very strongly suggest changing the form to use a different name for the field than 'action' if at all possible instead.

var form = document.forms.myForm;
var action = form.getAttribute('action');
if (action === form.elements.action) {
       // getAttribute broken;
       var string = form.outerHTML;
       return string.match(/action=(.*?)[> ]/)[1];
} else {
       return action;
}

That regular expression might not be robust enough. So test it hard if you do use it.




回答4:


I've just found another way: using or cloning the readAttribute method available in prototypejs.



来源:https://stackoverflow.com/questions/1378155/reading-form-action-property-in-ie6-if-form-has-a-field-named-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!