简体   繁体   中英

Change text of span element when clicking on it using jquery

This is my HTML code:

<div id="trashico">
    <img class="deskico" src="images/trashico.png"/>
    <p><span class="caption">Trash</span></p>
</div>

Here I want to use jQuery to change the text of the span when I click on the div . So what jQuery should I have to write?

You can do like this

$('#trashico').click(function(){
   $(this).find('span').text('your text');
});

You can change the text of the span on the click event -

$('#trashico').on('click', function() {
    $(this).find('span').text('new text');
})

Fiddle

write the folowing click event

$('#trashico').click(function(){
   $('.caption').text('What ever new name you want');
})

Update answer

As for what you try to achieve is sort of the windows F2 functionality. Try the following logic. You would have to implement it using the base idea I've given.

$('#trashico').click(function(){
    $(this).addClass('active'); //Add a seperate class to identify on what is clicked
})

$(document).keyup(function(e){
   if(e.keycode == 113 && $('.active').length > 0){
      $('.caption').text('change name');
   }
})

The above code will add a class to the clicked icon on your page. Sort of selected folder on windows. Then there is a keyup event bound to the document where it'll listen to what keys are pressed. when it hits 113 ( is the keycode for F2 ) then the if condition would be true and you would be able to change the name.

This is the basic logic of the OS renaming function. You would have to go through this base to achieve your requirement.

 $('#trashico').click(function() { $('#trashico > p > span').text("changed text"); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="trashico"> <img class="deskico" src="images/trashico.png" /> <p><span class="caption">Trash</span> </p> </div>

Try the following solution. Here we are changing the text of span tag with class caption :

$("#trashico").click(function(){
   $(this).find(".caption").text('New Text') }
});

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