通过jQuery获取元素的背景

时间:2016-06-04 13:01:36

标签: javascript jquery

我想在点击它之后提醒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>

2 个答案:

答案 0 :(得分:1)

你的HTML错了。 li元素必须包含在ulolmenu元素中。请记住,在您的示例中this引用全局对象(窗口)。您可以将this传递给函数以引用DOM元素。还要避免使用内联javascript和css:

&#13;
&#13;
$('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;
&#13;
&#13;

<强>参考

li element

答案 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>