开发者

jQuery noob: (this).replacewith am I doing it wrong?

开发者 https://www.devze.com 2023-02-12 17:14 出处:网络
I\'ve been learning more and more about jQuery but here I\'ve become stuck. I have a code to change the color of a div when a checkbox is cliked, that works fine.

I've been learning more and more about jQuery but here I've become stuck.

I have a code to change the color of a div when a checkbox is cliked, that works fine.

After this I want to be able to change the contents of a textarea on focus, I tried this:

    //textarea
    $("textarea").focus(function(){开发者_运维知识库
        if ($(this).contains('Skriv valg av headset her')){
         $(this).replaceWith('');
    });  

But there is no effect. Do I have some syntax errors or am I taking the wrong approach?

jsFiddle example here.


There's the $.contains function and the :contains selector, but no jQuery.fn.contains. You're looking for val here I believe:

$('textarea').focus(function(){
    var t = $(this);

    if(t.val().indexOf('Skriv valg av headset her') !== -1) {
        t.val('');
    }
});

replaceWith is also wrong here - if that were to work (and it shouldn't I believe because it takes either a DOM element or a HTML text) it would remove the textarea element (which is better done with remove anyway)


Try this:

//textarea
$("textarea").focus(function(){
    var $this = $(this); // Always cache your selector

    if ($this.contains('Skriv valg av headset her'))
    {
        $this.val('');
    }
}); 
0

精彩评论

暂无评论...
验证码 换一张
取 消