2014-04-19 24 views
0

Demo fiddlejQuery的不刪除強調的附加項目

HTML:

<div id = 'box' class = 'hide'> 

    <button id = 'add'>add</button> 

    <div class = 'entry'> 
     <input type = 'text' class = 'name' placeholder = 'name'> 
     <input type = 'text' class = 'email' placeholder = 'email'> 
    </div> 

</div> 

JS:

$("#add").click(function() { 
    $("#box").append("<div class = 'entry'>" 
        + "<input type='text' class='name' placeholder='name' spellcheck='false'></input>" 
        + "<input type='text' class='email' placeholder='email' spellcheck='false'></input>" 
        + "</div>"); 
}); 

$('#box .entry input[type=text]').blur(function() { 
     if ($(this).val().length > 0) { 
     $(this).css('border-bottom', '3px solid transparent'); 
    } else { 
     $(this).css({ 
      borderBottom: '3px solid blue' 
     }); 
    } 
}); 

一個輸入框,大幹快上的模糊強調,如果它是空白。儘管這種效果不適用於新添加的輸入。這是爲什麼發生?

回答

2

您應該使用事件委派。

使用.on();

這樣做:

$('box').on('blur','#box .entry input[type=text]',function() { 
    if ($(this).val().length > 0) { 
     $(this).css('border-bottom', '3px solid transparent'); 
    } else { 
     $(this).css({ 
      borderBottom: '3px solid blue' 
     }); 
    } 
}); 

Demo

.blur()是重視,忘記而.on()是動態的。

+0

這段代碼將聽文檔中的所有模糊事件。正確的做法是將輸入元素插入到表單中,並將模糊偵聽器添加到表單元素上。因爲除了文檔之外,表單元素可以收聽模糊元素。 – user2975123

+0

@ user2975123,我現在縮小了範圍。 –

+0

對不起,我的壞,模糊和鼠標不能從表單中聽。無論如何,我堅持把輸入放在表單中的建議。 – user2975123

0

因爲您還需要將blur()重新綁定到新添加的元素。

<script> 

rebind_blur(); 
$("#add").click(function() { 
    $("#box").append("<div class = 'entry'>" 
       + "<input type='text' class='name' placeholder='name' spellcheck='false'></input>" 
       + "<input type='text' class='email' placeholder='email' spellcheck='false'></input>" 
       + "</div>"); 

    rebind_blur(); 
}); 

function rebind_blur(){ 
    $('#box .entry input[type=text]').blur(function() { 
     if ($(this).val().length > 0) { 
      $(this).css('border-bottom', '3px solid transparent'); 
     } else { 
      $(this).css({ 
       borderBottom: '3px solid blue' 
      }); 
     } 
    }); 

} 

jsFiddle

1

jQuery將掃描文檔,一旦在頁面加載附加賽事,但爲了跟蹤新的元素,你將需要使用。對()方法:

$('document').on('blur', '#box .entry input[type=text]', function() { 
    //... 
});