开发者

Custom HTML Attributes,: Firefox vs. IE

开发者 https://www.devze.com 2022-12-14 06:19 出处:网络
What changes do I have to make to the following simple HTML page to get Firefox to read and set a custom attribute as it does in IE?

What changes do I have to make to the following simple HTML page to get Firefox to read and set a custom attribute as it does in IE?

<!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">

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Original Value</title>
</head>

<body>

<div MyAttribute="Original Value"  id="Label1"&开发者_开发技巧gt;Hello World</div>

<form method="post">
    <table style="width: 100%">
        <tr>
            <td>
            <input name="Button1" onclick="button1_click();" type="button" value="button" /></td>
        </tr>
    </table>
    <script type="text/javascript">
function button1_click(){

alert("Enter");
//alert("Label1.MyAttribute " + Label1.MyAttribute);
alert(Label1.getAttribute("MyAttribute"));

Label1.MyAttribute = "Updated";
alert("Label1.MyAttribute " + Label1.MyAttribute);

}
</script>
</form>

</body>

</html>


You've discovered getAttribute but you need to retrieve the element with document.getElemenById and you need to use setAttribute to modify the attribute.

function button1_click()
{
  alert("Enter");
  var label1 = document.getElementById("Label1"); 
  alert(label1.getAttribute("MyAttribute"));
  label1.setAttribute("MyAttribute", "Updated");
  alert("Label1.MyAttribute " + label1.getAttribute("MyAttribute"));
}


You need to assign node instance to the Label1 variable:

var Label1 = document.getElementById("Label1");

Also, when working with DOM, do not set values to properties, better do this with, setAttribute function


Your markup would be invalid. I've seen people do this sort of thing before but have never tried to understand it for that reason. How can you force any application to understand the it unless you used a different mime-type? And what about other browsers?


Try:

function button1_click(){
    alert("Enter");

    var label = document.getElementById('Label1');
    alert(label.getAttribute("MyAttribute"));
    label.MyAttribute = "Updated";
    alert("Label1.MyAttribute " + label.MyAttribute);

}

IE seems to search element IDs (and probably names) when you use an undefined global variable in your JavaScript. Firefox does not.

You could argue that either behavior is correct, but I would have to side with Firefox in this one. I don't like browsers assuming things about my code. Only makes minor errors, like the once in your original code, harder to spot.

0

精彩评论

暂无评论...
验证码 换一张
取 消