简体   繁体   中英

Jquery change html tag

I have structure like this:

<div id="mali_oglasi">
    <?php foreach ($mgs as $key) : ?>
    <p class="mali_oglas">
        <span class="name"><?php echo $key['name'] ?></span>
        <span class="body"><?php echo $key['body'] ?></span>
        <span class="contact_author"><?php echo $key['contact_author'] ?></span>
        <span class="date_created"><?php echo $key['date_created'] ?></span>
        <span class="date_expires"><?php echo $key['date_expires'] ?></span>
        <span class="email"><?php echo $key['email'] ?></span>
    <?php foreach ($lokacija as $lok) : ?>
    <?php if($lok['id_location'] == $key['location_id']) : ?>
    <span><?php echo $lok['name'] ?></span>
    <?php endif ?>
    <?php endforeach; ?>

    <?php foreach ($kategorija as $kat) : ?>
    <?php if($kat['id_category'] == $key['category_id']) : ?>
    <span><?php echo $kat['name'] ?></span>
    <?php endif ?>
    <?php endforeach; ?>
    <a class="obrisi" id="<?php echo $key['id_global_info'] ?>">Obrisi</a>     
    <a class="izmeni" id="<?php echo $key['id_global_info'] ?>">Izmeni</a>  
</p>
    <?php endforeach; ?>
</div>

When <a class="izmeni" id="<?php echo $key['id_global_info'] ?>">Izmeni</a> is clicked it need to change span to input or textarea. How can I do this?

You would use jQuerys .replaceWith() -method. Eg

$('.izmeni').on('click', function() {
    $('span').replaceWith('<input />');
});

You can also walk up the DOM in your click handler to get to your target element:

$('.izmeni').on('click', function() {
    $(this).closest('span').replaceWith('<input />');

    // or:
    //  $(this).closest('p').find('span').replaceWith('<input />');
    // etc.
});

Or something similar. Take a look at jQuerys various tree traversal functions .

Use the click handler :

$(document).ready(function() {
    $('#<?php echo $key['id_global_info'] ?>').click(function() {
       $(selectorforspan).html('the new html');
    });
});

This could use the .html() function to set the HTML contents of the element specified in the selector ( $(selectorforspan) ).

You should do

$('a.izmeni').click(function(){
    $('span.classofyourspan').replaceWith($('<input>', { type : "text", name: "yourname"}));
});

There are a few ways you could do, but using jQuery's replaceWith method looks like the best way. There's even an example on their documentation: http://api.jquery.com/replaceWith/

$('.izmeni').click(function() {
    $(this).replaceWith('<span>'+$(this).text()+'</span>');
});
$('a.izmeni').live('click', function() {
 var span = $('p.mali_oglasi span');
 var inputBox = $('<input />').attr('value', span.text());

 span.replaceWith(inputBox);
});

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