这里是示例 http://jsfiddle.net/apye01n0/6/
首先是html
<div id="large_photo" style="width:100px; height:100px;" > To show one large photo </div>
<div id="base_64_string0" class="thbn_photo" style="float:left;
background-color: #b0c4de; height: 50px; width: 50px; margin: 0 3px 3px 0; "></div>
想要点击class="thbn_photo"
,获取id
的值并使用下面的jquery代码中的值。我已经定义了 jquery 变量,变量名称是单击的 id 的值。
这是 jquery 变量
base_64_string0 = 'R0lGODlhRgAzAJE..';
这是剩余的 jquery 代码
$(document).on('click', '.thbn_photo', function(){
alert( this.id );
//$("#large_photo").css("background-image", "url('data:image;base64," + base_64_string0 + "')");//This works
$("#large_photo").css("background-image", "url('data:image;base64," + this.id + "')");//This does not work
});
点击 alert( this.id );
我看到 base_64_string0
。
所以我希望如果我在 url('data:image;base64,"+ this.id + "')
中插入 this.id
我会得到相同的结果as url('data:image;base64,"+ base_64_string0 + "'
.
使用 url('data:image;base64,"+ base_64_string0 + "')
一切正常(我手动编写变量名称 (base_64_string0
))。
但是 url('data:image;base64,"+ this.id + "')
不起作用。在生成的源代码中,请参阅 background-image: url("data:image;base64,base_64_string1");">
。如何使此代码正常工作?
最佳答案
您希望使用 id 参数作为变量名称。这是错误的。
img = {
base_64_string0 : 'R0lGODlhRgAzAJE..'
}
和
"url('data:image;base64," + img[this.id] + "')"
关于jquery。单击 div,获取 div 的 id 并将该 id 用作 jquery .css ("background-image"的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28403297/