Jquery add class attribute src img
I tried to add a class to the开发者_如何转开发 following HTML code with jquery:
<img style="position: absolute; left: 0px; top: 0px; width: 37px; height: 94px; -moz-user-select: none; border: 0px none; padding: 0px; margin: 0px;" src="http://maps.gstatic.com/intl/it_ALL/mapfiles/smc.png">
I tried doing this with this code and a few other ways but it did not work
<script>
$( 'img[src="http://maps.gstatic.com/intl/it_ALL/mapfiles/smc.png"]' ).addClass("selected");
</script>
where is my error?
The most easy way is to add an identifier to your image tag. This can be a class or ID:
<img id="mapfile-image" src="http://maps.gstatic.com/intl/it_ALL/mapfiles/smc.png">
This way you can add your class by targeting the identifier:
$('#mapfile-image').addClass("selected");
The problem is you are missed to add ready function :
Try this :
<script>
$(function(){ // ready function
$('img[src="http://maps.gstatic.com/intl/it_ALL/mapfiles/smc.png"]').addClass("selected");
});
</script>
Your code :
<script>
$( 'img[src="http://maps.gstatic.com/intl/it_ALL/mapfiles/smc.png"]' ).addClass("selected");
</script>
your code get executed before your image element loaded. Hence try putting you jquery code inside ready function.
Try this:
<script>
$(function() {
$("img[src='http://maps.gstatic.com/intl/it_ALL/mapfiles/smc.png']").addClass("selected")
});
</script>
You don't specify anywhere when you want this action to take place. Obviously you must wait for the document to load so the img will exist on the page before you add a class to it. this can be done by changing your script to:
<script>
$(document).ready(function(){
$('img[src$="http://maps.gstatic.com/intl/it_ALL/mapfiles/smc.png"]').addClass("selected");
});
</script>
Notice that we are waiting for the document to be ready before we add the class to it.
Try this:
$(document).ready(function(){
$('img[src*="http://maps.gstatic.com/intl/it_ALL/mapfiles/smc.png"]').addClass('selected');
});
Hope that helps :)
精彩评论