当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery. Click on div, take id of the div and use the id as part of jquery .css("background-image"

问题描述:

Here is example http://jsfiddle.net/apye01n0/6/

At first 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>

Want on click on class="thbn_photo", get value of id and use the value in below jquery code. I have defined jquery variable and variable name is value of the clicked id.

Here is jquery variable

base_64_string0 = 'R0lGODlhRgAzAJE..';

Here is remaining jquery code

$(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

});

On click with alert( this.id ); i see base_64_string0.

So i expect if i insert this.id in url('data:image;base64," + this.id + "') i would get the same as url('data:image;base64," + base_64_string0 + "'.

With url('data:image;base64," + base_64_string0 + "') all works (i manually wrote variable name (base_64_string0)).

But with url('data:image;base64," + this.id + "') does not work. In generated source see like background-image: url(&quot;data:image;base64,base_64_string1&quot;);">. How to get this code to work?

网友答案:

You can not use a parameter value as the variable name. Instead you can map that parameter to some value. I have used an array of images with the parameter value as a key to the image code. See DEMO

var images = [];
images['base_64_string0'] = 'R0lGODlhRgAz';
网友答案:

You want use id parameter like a name of variable. This is mistake.

img = {
    base_64_string0 : 'R0lGODlhRgAzAJE..'
}

and

"url('data:image;base64," + img[this.id] + "')"

http://jsfiddle.net/apye01n0/15/

网友答案:

Hey brother first Pass this.id to one variable and pass the value of that variable instead of this.id like given below :

$(document).on('click', '.thbn_photo', function(){
alert( this.id );
 var str=this.id; //Here is declaration of variable
//$("#large_photo").css("background-image", "url('data:image;base64," + base_64_string0 + "')");//This works
$("#large_photo").css("background-image", "url('data:image;base64," + str + "')");

});
分享给朋友:
您可能感兴趣的文章:
随机阅读: