简体   繁体   中英

Hiding img tag inside div onClick() using jQuery

i tried to show and hide img tag in below code

<div id='userview_'<?php echo $userId; ?>>
    <img src="css/user/images/user1.svg">
</div>

i wrote jquery to show img like dis

var userId='<?php echo $userId; ?>';
jQuery('#userview_'+userId ' img').css('src','url(css/user/images/user1.svg) no repeat center');

but not working

and also i need to know hide this img tag (only) in onClick()

Src is an attribute, so you need to do something like below and give proper image path,

var userId='<?php echo $userId; ?>';
jQuery('#userview_'+userId ' img').attr('src','css/user/images/user1.svg');

try

jQuery('#userview_'+userId +' img')

                          ^^^^ you messed    

use attr

HTML

<div id='userview_33'>
    <img src="css/user/images/user1.svg" />
</div>

JS

var userId = 33;

jQuery('#userview_' + userId +' img').attr('src', 'url(css/user/images/user3.svg) no repeat center'); 

First in your html place php tag inside of '' so like this <div id='userview_<?php echo $userId; ?>'> <div id='userview_<?php echo $userId; ?>'>

Then you can do something like this

jQuery('#userview_'+userId+' img').click(function(){
    jQuery(this).hide();
});

Where You have:

var userId='< ? php echo $userId; ?>';

jQuery('#userview_'+userId ' img').css('src','url(css/user/images/user1.svg) no repeat center');

remember that the PHP script work only in PHP files. You can do like this: part of index.php

<div class="imgContainer"></div>
...
<script>var userId = <?php userId?> </script>

and in JS file:

jQuery('#userview_'+userId +' .imgContainer').css('src','url(css/user/images/user1.svg) no repeat center');

and if You want on click event:

jQuery('#userview_'+userId ' imgContainer').on('click', function(){
   /*some code*/
});

also walk thru this tutorial: http://try.jquery.com/levels/1/challenges/1

<div id='userview_'<?php echo $userId; ?>>
    <img src="css/user/images/user1.svg" />
</div>
<a href="#" class="testclick">Click</a>
$('.testclick').click(function(){
var userId='<?php echo $userId; ?>';
    $('#userview_'+userId+' img').hide();
});

Finally I found myself a method

 jQuery('#userview_'+userId , "'<img src=css/user/images/user1.svg>'").remove();

When i need to show it agin.. i used

jQuery('#userview_'+userId).append('<img src="css/user/images/user1.svg>">');

thank you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM