1

Function: When click a button, the alt value of it will added to text area and it will show its live preview with div and the id is its alt value. On my code there is a problem, when i click the button it inserted the whole code which is , id like to remove the div tag and i like only to show the alt code but in preview it show well the desired div. Please help me! Thanks

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
    $('.image').click(function(e){
        var tav    = $('#image_code').val(),
            strPos = $('#image_code')[0].selectionStart;
        front  = (tav).substring(0,strPos),
            back   = (tav).substring(strPos,tav.length); 
        $('#image_code').val(front + '<div id=\"' + $(this).attr("alt") + '\"></div>' + back).trigger('keyup');
    });
    $('#image_code').keyup(function() {
        $('#image_preview').html( $(this).val() );
    });
});
</script>

<style>
#one{
background-color: black;
width: 50px;
height: 50px;
border-radius: 2px;
}
#two{
background-color: red;
width: 50px;
height: 50px;
border-radius: 2px;
}
#three{
background-color: blue;
width: 50px;
height: 50px;
border-radius: 2px;
}
</style>

<textarea id="image_code"></textarea>
<div id="image_preview"></div>
<button id="1" class="image" title="1" alt="one">1</button>
<button id="2" class="image" title="2" alt="two">2</button>
<button id="3" class="image" title="3" alt="three">3</button>
4

1 回答 1

1

这一切似乎都很奇怪,但从我能理解你的问题的最好情况来看,这是你希望实现的吗?

$('.image').click(function(e){
    $('#image_code').val($(this).attr("alt")).trigger('keyup');
});
$('#image_code').keyup(function() {
    var tav    = $('#image_preview').html();
    strPos = $('#image_code')[0].selectionStart;
    front  = (tav).substring(0,strPos),
    back   = (tav).substring(strPos,tav.length); 
    $('#image_preview').html(front + '<div id=\"' + $(this).val() + '\"></div>' + back);
});

http://jsfiddle.net/U3aEg/

于 2013-05-10T07:46:42.357 回答