点击= "function()"不起作用,但 href= "javascript: function()"工作正常?



我写了一个函数,它很简单地改变了图像的样式属性,当点击。

    document.getElementById("normal" + current).setAttribute('style', 'display: block;');

current是函数的参数。例如changeImage (10)而我们想要更改其样式的元素image的最终id为"normal10"。

要使它显示,基本上就像一开始设置为display: none一样,我们需要将其更改为block。

那么,我有两个实例,我调用方法changeImage(current)

    <a href="#" onclick="changeImage(10);"><img src="xyz"></img></a>

    <a href="javascript: changeImage(10);"><img src="xyz"></img></a>

这两个功能在Chrome &在Opera中,显示属性两次都被更改。

然而,在其他浏览器如IE或Firefox上,display属性似乎只在我们有

的地方被改变
    <a href="javascript..."> 

而不是通过onclick调用方法的地方。我试着改成:

    document.getElementById("normal" + current).style.display="block";

可惜没有用。

我不认为javascript本身有问题。因为该函数在href.

中调用时执行良好。

有人有什么想法吗?

谢谢!

编辑:使用jQuery完成后,代码执行,但图像的样式仍然没有改变。作品在Chrome &Opera还在,但火狐不在了。IE .

我给被点击执行函数的图像一个id为"img"。

    <img id="img" src="..."></img>

和执行函数的代码放在以下标签中(在document ready function中):

    $('#img').click(function(){}

代码被执行,但样式只在特定浏览器上从none更改为block。

既然你要求jQuery解决方案。这里有一个:

<style>
  /* hide all elements with id starting by normal... */
  [id^=normal] { display: none; }
</style>
<!-- place the http protocol if you are on localhost -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js" ></script>
<script>
   $(document).ready(function () {         // when page is fully loaded
     // define a click event for any
     // anchor with a class "shownormal" and attribute "data-id" defined
     $("a.shownormal[data-id]").click(function (event) {
         $("#normal" + $(this).attr('data-id')).show();
         event.preventDefault();
     });
   });
</script>

,标记可以是

<a href="#" class="shownormal" data-id="10"><img src="xyz"></img></a>
<a href="#" class="shownormal" data-id="15"><img src="xyz"></img></a>

使用jQuery和不使用jQuery的jsFiddle 示例

http://jquery.com/

尝试使用这个,

$("#normal"+current).css("display","block")

相关内容

最新更新