单击后,我想提醒LI元素的背景,但脚本不起作用。可能是什么问题?
<li onclick="getVkPhotoUrl()" style="background-image: url(http://lorempixel.com/400/400/people)" class="block">
</li>
<li onclick="getVkPhotoUrl()" style="background-image: url(http://lorempixel.com/400/400/food)" class="block">
</li>
<li onclick="getVkPhotoUrl()" style="background-image: url(http://lorempixel.com/400/400/food)" class="block">
</li>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function getVkPhotoUrl(){
var bg = $(this).css('background-image');
bg = bg.replace('url(','').replace(')','');
alert(bg);
}
</script>
最佳答案
将onclick更改为onclick = yourMethodName(this)
并用作yourMethodName(ctrl)
,并在方法定义中使用ctrl
代替this
。
<li onclick="getVkPhotoUrl(this)" style="background-image: url(http://lorempixel.com/400/400/people)" class="block">
</li>
<li onclick="getVkPhotoUrl(this)" style="background-image: url(http://lorempixel.com/400/400/food)" class="block">
</li>
<li onclick="getVkPhotoUrl(this)" style="background-image: url(http://lorempixel.com/400/400/food)" class="block">
</li>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function getVkPhotoUrl(ctrl){
var bg = $(ctrl).css('background-image');
bg = bg.replace('url(','').replace(')','');
alert(bg);
}
</script>
关于javascript - 通过jQuery获取元素的背景,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37630545/