JQuery .attr not working in Chrome

1.5k views Asked by At

I'm using a :regex library (found here) to select elements that have IDs starting with P and having at least 5 digits afterward. Then, I use .attr to add on some attributes.

$(document).ready(function() {
$('img:regex(id,P[0-9][0-9][0-9][0-9]+)').attr("onmouseover", "show\(this\,2\,0\)");
$('img:regex(id,P[0-9][0-9][0-9][0-9]+)').attr("onmouseout", "hide\(this\)");
});

This works in Firefox, but not Chrome. (Haven't tested IE yet.)

I tried using [0].setAttribute instead, and it works to an extent, but then for some reason it only selects the first instance of the regex.

Does anyone have a more compatible solution?

6

There are 6 answers

2
jAndy On BEST ANSWER

Whatever that plugin does, it looks terribly slow. I would rather recommend to select all image nodes and then filter them with jQuery .filter()help, this has to be faster and I think it's still more readable at all. Could look like:

$('img').filter(function(index) {
    return this.id.charAt(0) === 'P' && !isNaN(this.id.slice(1,6));
}).hover(function() {
     $(this).show();
}, function() {
     $(this).hide();
});

Demo: http://www.jsfiddle.net/snMCM/

Performance benchmark: http://jsperf.com/regex-vs-jquery-filter

0
Dutchie432 On

regEx aside, you should use the jQuery .hover() function, not the .attr() function. I've incorporate the .hover() function as well as the regEx provided by kirilloid

$(document).ready(function() {
    $('img:regex(id, P\d{5,})').hover(function(){
        show( $(this), 2, 0);
    }, function(){
        hide( $(this) );
    });
});
1
Andy Baird On

I'm not sure you can attach javascript handlers using attr, but that sounds like a very long way of doing it. Give this a shot:

$('img:regex(id,P[0-9][0-9][0-9][0-9]+)').hover(function() {
    show(this,2,0);
},function() {
    hide(this);
}); 
0
Guillaume86 On

I know it doesn't really answer your question but...

Add a class to the elements you want to select.

1
Neil On

Why not just use filter() instead of the :regex library? This should work in all browsers. e.g.

var $imgs = $('img').filter(function(){return this.id.match(/^P\d\d\d\d\d/);});
$imgs.attr("onmouse.......
0
Nono On

Try This: (Working in all browsers)

        $(window).load(function () {
        //your script or function

                    $("your_html_tag").attr({
                            width : "your-width",
                            height : "your-height",
                            alt: "Online Teacher"
                        });
        });

Rather than

        $(document).ready(function () {
       //your script or function

                    $("your_html_tag").attr({
                            width : "your-width",
                            height : "your-height",
                            alt: "Online Teacher"
                        });
        });