Javascript working on Firefox but not in Chrome an

2019-08-28 21:46发布

I have javascript that working fine in Firefox 3.x.x, but it does not work in IE*, Chrome, Safari. Simple alert work before calling function. Here is the code

function showDiv(div){
 //alert(div);
 document.getElementById(div).style.visibility='visible';
 document.getElementById(div).style.height='auto';
 document.getElementById(div).style.display='block';}
function hideDiv(div){
 //alert(div);
 document.getElementById(div).style.visibility='hidden';
 document.getElementById(div).style.height='0px';
 document.getElementById(div).style.display='none';
}

here is the html page code

<td align="center"><a onclick="showDiv('<?=$val['keyname']?>')" style="cursor:pointer;">Edit</a></td>

if I put alert() before showDiv('<?=$val['keyname']?>') then alert box is displayed but the function is not called in other browsers other than fire fox

Please tell me the solution for this.

3条回答
趁早两清
2楼-- · 2019-08-28 22:24

The syntax looks okay to me.

Make sure there are not multiple elements with the same ID in the document and that your element IDs are valid.

查看更多
戒情不戒烟
3楼-- · 2019-08-28 22:25

There is nothing inherently wrong in the code you have posted. I suggest you post a reproduceable non-working example: the problem will be elsewhere in the page. Maybe the div ID string isn't unique (this is invalid HTML and will make behaviour unreliable); maybe there's some other script interfering, maybe you have event code firing this that's not written in a cross-browser way

However your attempts to hide an element in three different ways seem like overkill to me. Just a single display change would do it fine.

Another way to do it is to set className='hidden' or '', and use a CSS rule to map that class to display: none. The advantage of this is that you don't have to know whether the element in question is a <div> (that should revert to display: block), a <span> (that should revert to display: inline) or something else. (The table-related elements have particular problems.)

查看更多
Animai°情兽
4楼-- · 2019-08-28 22:29

Maybe you could try that:

function showDiv(div) {
    var obj = document.getElementById(div);
    if (obj) {
        obj.style.display = "block";
        obj.style.height = "auto";
    } else {
       alert("DIV with id " + div + " not found. Can't show it.");
    }
}

function hideDiv(div) {
    var obj = document.getElementById(div);
    if (obj) {
        obj.style.display = "none";
    } else {
       alert("DIV with id " + div + " not found. Can't hide it.");
    }
}

Do not call document.getElementById several times in the same function, use a variable to store the div element.

The if (obj) test will only execute the code if it has been found by document.getElementById(...).

查看更多
登录 后发表回答