jQuery load()在textarea上没有按预期工作

I'm trying to get user content from PHP file with load() function and show it in the textarea which works fine however same process won't work if the user type something in the texarea beforehand. Anyone has a solution to it?

For example: Type something in textarea and click links which won't change the content of texarea.

Thanks in advance

HTML

<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>

<script type="text/javascript">
function show_content(display_field, id)
{
    $('#' + display_field).load('data.php?id=' + id);
}
</script>


<a href="#nogo" onClick="show_content('content_area', '1')" title="View">User 1</a>
<a href="#nogo" onClick="show_content('content_area', '2')" title="View">User 2</a>
<a href="#nogo" onClick="show_content('content_area', '3')" title="View">User 3</a>

<textarea id="content_area" rows="10" cols="10"></textarea>

PHP

<?php
$content[1] = 'This belongs to User 1';
$content[2] = 'This belongs to User 2';
$content[3] = 'This belongs to User 3';

echo $content[$_GET['id']];
?>

Your problem is that load() sets the html rather than the value.

You could use this:

function show_content(display_field, id) {
    $.get( 'data.php?id=' + id, function( data ) {
        $('#' + display_field).val(data);
    });
}

.get()

You did not state what "won't work" means. If you mean the textarea contents sometimes appears incorrectly, I suspect it is because you are launching three asynchronous calls to $(#xxx).load((); Each will execute independently and in the future update your textarea in a random order.

Instead do something like this:

 $('#temp').load('data.php?id=' + id, function (responseText, textStatus, XMLHttpRequest) {
     $('#display_field).val($('#temp').val());
);

Each result will execute serially, loading in your results. They may not be in the order you called them though.