2014-12-04 90 views
0

我想添加图像到按钮,一旦点击使用jquery.I无法添加图像。将背景图像添加到jquery中的按钮

这里是jQuery代码

$('#b2').click(function(){ 
alert("b2 am called"); 
$(this).addClass("bg1"); 
}); 

下面是CSS

.bg1 
{ 
background-image: url(info.jpg); 
background-repeat: no-repeat; 
border: none;  
} 

input#b2 
{ 
position:absolute; 
left:370px; 
top:130px; 
width:90px; /*same as the height*/ 
height:90px; 
} 

这里是HTML代码

<div id="level_1"class="Level1"> 
<input type="button" id="b2" value="" name="b2" > 
</div> 

这里是:JS Fiddle

+1

尝试使用'!important'在'.bg1'类 – 2014-12-04 11:31:40

+1

适用于[Fiddle](http://jsfiddle.net/chipChocolate/0wmao9ny/)。你看到'alert()'吗?如果没有,你不包括jQuery库的链接。 – 2014-12-04 11:34:24

+0

我可以看到警报 – 2014-12-04 11:37:02

回答

0

我想你可能为m在你的工作示例中发布jQuery库。我得到了它在这里工作:使用

$('#b2').click(function(){ 
    alert("b2 am called"); 
    $(this).addClass("bg1"); 
}); 

JSFIDDLE
input.bg1 
{ 
    background:url('http://i.ytimg.com/vi/UFS6Ky7OnAw/mqdefault.jpg'); 
} 

完整的解决方案:

<style> 
    input#b2 
{ 
position:absolute; 
left:370px; 
top:130px; 
width:90px; /*same as the height*/ 
height:90px; 
background:#fff; 
} 

input.bg1 
{ 
    background:url('http://i.ytimg.com/vi/UFS6Ky7OnAw/mqdefault.jpg') !important; 
} 
</style> 

<div id="level_1"class="Level1"> 
    <input type="button" id="b2" value="" name="b2" /> 
</div> 

<script src="http://code.jquery.com/jquery.min.js"></script> 
<script> 
    var $ = jQuery 
    $('#b2').click(function(){ 
     alert("b2 am called"); 
     $(this).addClass("bg1"); 
    }); 
</script> 
+0

其中Jquey图书馆? – 2014-12-04 11:52:29

+0

尝试在你的javascript之前添加'' – babusi 2014-12-04 11:54:32

+0

我添加了上面的库,但仍然无法正常工作 – 2014-12-04 11:58:30

1

这似乎有些修改后的打算工作:

http://jsfiddle.net/dtq38yvz/7/

<div id="level_1" class="Level1"> 
    <input type="button" id="b2" value="" name="b2"> 
</div> 

$('#b2').click(function(){ 
    $(this).addClass("bg1"); 
}); 

#b2 
{ 
    position:absolute; 
    left:370px; 
    top:130px; 
    width:90px; /*same as the height*/ 
    height:90px; 
    background-color:#fff; 
} 

.bg1 
{ 
    background:url('http://i.ytimg.com/vi/UFS6Ky7OnAw/mqdefault.jpg') no-repeat center center; 
}