开发者

JQuery - Add an onmouseover attribute to an input element where type equals image

开发者 https://www.devze.com 2022-12-15 00:36 出处:网络
开发者_运维知识库Is it possible to add an onmouseover attribute to an input element where type equals image?
开发者_运维知识库

Is it possible to add an onmouseover attribute to an input element where type equals image?

I have created the following code but it does not add the attribute.

    <script language="javascript" type="text/javascript">
        $(document).ready(function() {
            $("input").each(function(i) {
                if (this.src.indexOf('/images/icons/thumbs.png') != -1) {
                    $(this).attr({ onmouseover: "images/icons/thumbsover.png" });
                    $(this).attr({ onmouseout: "images/icons/thumbsout.png" });
                }
            });
        });
    </script>   


You are misunderstanding the onmouseover attribute.

The onmouseover attribute is used in HTML to provide Javascript code that executes when the mouse moves over the element.

In jQuery, you should use the event methods instead.

You actually want to write the following:

$(":image[src='/images/icons/thumbs.png']").hover(
    function() { this.src = 'images/icons/thumbsover.png' },
    function() { this.src = 'images/icons/thumbsout.png' }
);

For more information, read about selectors.


Here some code that will give you the desired effect.

$(document).ready(function() {
    $("input:image[src$=thumbs.png]").hover(function() {
        $(this).attr("src", "images/icons/thumbsover.png")
    }, function(){
        $(this).attr("src", "images/icons/thumbsout.png")    
    });
});        

PS. I would try and achieve the efect using pure CSS


See jQuery's Selectors/Attribute documentation for more information.

$("input[type='image']").hover(
  function () {
    //mouseover
  },
  function () {
    // mouseout
  }
);


Yep, very easy indeed with selectors:

$('input[type=image]').mouseover(function(){
    ...
}).mouseout(function(){
    ...
});

in this case, it seems you want to change the background image:

$('input:image[src=/images/icons/thumbs.png]').hover(function(){
    //Mouse Over
    $(this).attr('src','mouseoverimage.gif');
},
function(){
    //Mouse Out
    $(this).attr('src','mouseoutimage.gif');
});


Are you trying to change the source of the image when the user hovers it? Then try the following:

<script language="javascript" type="text/javascript">
    $(document).ready(function() {
        $("input").each(function(i) {
            if (this.src.indexOf('/images/icons/thumbs.png') != -1) {
                $(this).hover(
                  function(){ $(this).attr("src", "images/icons/thumbsover.png");},
                  function(){ $(this).attr("src", "images/icons/thumbsout.png");}
                );
            }
        });
    });
</script>
0

精彩评论

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