我想在点击它之后提醒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>
答案 0 :(得分:1)
你的HTML错了。 li
元素必须包含在ul
,ol
或menu
元素中。请记住,在您的示例中this
引用全局对象(窗口)。您可以将this
传递给函数以引用DOM元素。还要避免使用内联javascript和css:
$('ul li.block').on('click', function() {
var bg = $(this).css('background-image');
bg = bg.replace('url(', '').replace(')', '');
console.log(bg);
});
&#13;
ul li.block.people {
background-image: url(http://lorempixel.com/400/400/people);
}
ul li.block.food {
background-image: url(http://lorempixel.com/400/400/food);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="block people"></li>
<li class="block food"></li>
<li class="block food"></li>
</ul>
&#13;
<强>参考强>
答案 1 :(得分:1)
将其更改为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>