1

我是 JS / jQuery 的新手。

我试图实现的是,每次我按下“ Title”或“ Description”时,只会出现当前的文本区域消息。

我试图克隆原始的div,但我真的不知道在哪里或如何使用它,所以这个替换文本的想法似乎更容易实现。

正如我所说,我是网络编程的新手,我真的很成功。我不明白为什么以下代码不起作用:

http://jsfiddle.net/MceE9/

<div class="content"> 
<form method="POST" id="anunt">
    <table id="anunt">
        <tr id="title">
            <td> Title: </td>
            <td> <input type='text' name='title' id='titleClick'> </td>
        </tr>
         <tr id="description">
            <td> Description: </td>
            <td> <textarea rows="5" cols="40" id="descriptionClick" name="description"></textarea> </td>
        </tr>
        <tr>
        <td> <input type="submit" name="send" value="Send"> </td>
        </tr>
    </table>
</form>

var title;
var description;

$('#titleClick').one('click', function(){
        title = '<span id="text" style="font-weight: bold; font-size: 18px; color: red;">Title text</span>';
       $("#title").append(title);
       $('#description').html($('#description').html().replace(description, ''));
    });

$('#descriptionClick').one('click', function(){
        description = '<span id="text" style="float:left; font-weight: bold; font-size: 18px; color: red;"> Description text</span>';
        $("#description").append(description);
        $('#title').html($('#title').html().replace(title, ''));
});
4

3 回答 3

1

你可以这样做:

var text = {};

text['title'] = '<span id="text" style="font-weight: bold; font-size: 18px; color: red;">Title text</span>';
text['description'] = '<span id="text" style="float:left; font-weight: bold; font-size: 18px; color: red;"> Description text</span>';

$('input, textarea').on('focus', function() {
    $('#text').remove();
    $(this).parent().append(text[this.name]);
});

http://jsfiddle.net/dpatz/MceE9/4/

于 2013-08-27T16:01:12.060 回答
1

将您的 javascript 更改为以下内容:

$('#titleClick').on('focus', function(){
    $('#text').remove();
    $("#title").append('<span id="text" style="font-weight: bold; font-size: 18px; color: red;">Title text</span>');
});

$('#descriptionClick').on('focus', function(){
    $('#text').remove();
    $("#description").append('<span id="text" style="float:left; font-weight: bold; font-size: 18px; color: red;"> Description text</span>');
});
于 2013-08-27T15:55:36.830 回答
0

或者像这样的东西可以工作:

http://jsfiddle.net/MceE9/5/

var title;
var description;

$('#titleClick').on('click', function(event){
    event.stopPropagation();
    var textToDisplay = 'this is an error message';
    var $errorElement = $('span.title-text');

    $errorElement.text(textToDisplay);

    $('body').one('click', function() {
        $errorElement.text('');
    });

});

$('#descriptionClick').on('click', function(){
    // repeat for second element - or make a more generic function that works for both.
});
于 2013-08-27T16:09:10.377 回答