2016-09-17 52 views
0

我在jQuery中使用append方法來生成一些HTML輸入框;現在我想使用jQuery對這些輸入元素產生一些效果,但是我不能。這是我想要做的一個小例子。如果我使用append生成HTML元素,那麼我可以使用jQuery影響它們嗎?

<style type="text/css"></style> 
<style> 
.focus 
{ 
    background-color: green; 
} 
</style> 
<script src="alu_afric/Java/java.js"></script> 
<script> 
$(document).ready(function() { 
    $("button").click(function() { 
    $("#newHTML").append('<input type="text" placeholder="some text .."/>'); 
    }); 
    $("input").focus(function() { 
    $(this).addClass("focus"); 
    }); 
}); 
</script> 
<button>Click</button> 
<body> 
<div id="newHTML"></div> 
</body> 
+0

你可能只是有一個'輸入:重點{ 背景色:綠色; }'在CSS,那麼你就沒有必要擔心jQuery的 – Bassie

回答

0

事件偵聽器應該是

$(document).on('focus', 'input[type=text]', function() { 

而不是

$("input").focus(function(){ 

請檢查片斷進行更多的瞭解。

$(document).ready(function(){ 
 
    $("button").click(function(){ 
 
    $("#newHTML").append('<input type = "text" placeholder = "some text .."/>'); 
 
    }); 
 
    $(document).on('focus', 'input[type=text]', function() { 
 
    $(this).addClass("focus"); 
 
    }); 
 
});
.focus 
 
{ 
 
    background-color: green; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button>Click</button> 
 
<body> 
 
    <div id = "newHTML"></div> 
 
</body>

+0

謝謝回答,但它給了我同樣的結果 –

+0

的所以應該有使用$(文件)。在(「專注」,「輸入[類型=文本]',函數(){事件監聽器而不是$(「輸入」)。焦點(函數(){ –

+0

@ M-AmrMoussa你檢查過更新的答案嗎? –

0

當然可以。只要你先附加html,然後綁定你想要的事件。

$(document).ready(function(){ 
    $("button").click(function(){ 
//for safe calling lets add a class 
    $("#newHTML").append('<input type = "text" placeholder = "some text .." class="inpt-class"/>'); 
    //after the input is add to the page add an event for it 
    // either use or .on() or .focus() 
    $("input.inpt-class").focus(function(){ 
    $(this).addClass("focus"); 
    }); 
    }); 
}); 
0

如果使用appendTo方法,而不是您可以將輸入元素存儲在一個變量,並進行更改。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<style = "txt/css"></style> 
 
<style> 
 
.focus 
 
{ 
 
    background-color: green; 
 
} 
 
</style> 
 
<script src = "alu_afric/Java/java.js"></script> 
 
<script> 
 
$(document).ready(function(){ 
 
    $("button").click(function(){ 
 
    var input = $('<input type = "text" placeholder = "some text .."/>'); 
 
    input.appendTo("#newHTML"); 
 
    input.css('background', 'red'); 
 
    }); 
 
    $("input").focus(function(){ 
 
    $(this).addClass("focus"); 
 
    }); 
 
}); 
 
</script> 
 
<button>Click</button> 
 
<body> 
 
<div id = "newHTML"></div> 
 
</body>

相關問題