Pregunta

I have create a html page by using javascript to create the input box, and using jquery to assign the class to the input box then trying to using focus() by using the class name, but it's not working at all. When I click on the input box, alert is not pop up :(

Does anyone know what is going wrong here ? and how can I fix this issue?

html page:

  <table border="0" width="800">
    <tr>
        <td align="center">
            <div id="test">

            </div>       
        </td>
    </tr>
  </table>

javascript:

htmlValue = "<input maxlength='4' size='2' type='text'  id='startTime_1' value='" + startTime + "'  />";

$("#test").html(htmlValue );


$('#startTime_1').addClass('test1');


$('#test1').focus(function () {
    alert('inside');
});
¿Fue útil?

Solución

The following code:

$('.test1').focus(function () {
    alert('inside');
});

should instead be bound to #test first.

$('#test').focus('.test1', function () {
    alert('inside');
});

Since you are still using jQuery 1.4.2; you need to use .live() method for handlers.

The code shall be

$('#test').live('focus', '.test1', function () {

Otros consejos

If you want to add handlers to dynamically created content, you'll want to either add the handler after the content has been added or, more commonly done, just use event delegation. For jQuery, this means using .on:

$('.test1').on('focus', function () {
    alert('inside');
});

Here's the documentation to learn more about using .on.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top