1

我的最终范围是在单击后更改输入字段中的文本,从而将<div>容器替换为<form>容器。

但是表单创建之后,点击事件不再被触发

在这个jfiddle 中,我只发布了表单创建和检查 div 火灾的功能。有什么想法吗?

(还有任何提高代码可读性和效率的建议和意见总是很受欢迎,我是新手)。

斯特凡诺

代码: HTML

<body>
    <div id="pubbl">
        <div id="title"><h1>A sentence</h1></div>
        <div id="content">“Age is my alarm clock,” the old man said. “Why do old men wake so early? Is it to have one longer day?”
“I don’t know,” the boy said. “All I know is that young boys sleep late and hard”. Ernest Hemingway.</div>
    </div>
</body>
<button id="btn">show html</button>
<button id="cr">create form</button>

代码:JavaScript

$("#btn").click(function(){
    alert($("body").html());
    alert(there_is_form());
});

$("#cr").click(function(){
    crea_form();
});

$("#title").click(function(){
    alert("title fired");
});
$("#content").click(function(){
    alert("content fired");
});

function crea_form(){
    alert("function create form fired");
    if (there_is_form()) { return; };
    var test_div = document.getElementById('pubbl');
    var cont = test_div.innerHTML;
    test_div.innerHTML = '';    
    var form = test_div.appendChild(document.createElement('form'));
    form.name = 'input';
    form.action = 'target-etc';
    form.method = 'post';
    form.innerHTML = cont;
    input = form.appendChild(document.createElement('input'));
    input.type = 'submit';
    input.value = 'Submit';
};

function there_is_form(){
    return document.getElementsByTagName("form").length > 0;
};
4

1 回答 1

1

尝试这个,

$(function(){
    $(document).on('click',"#btn",function(){
        alert($("body").html());
        alert(there_is_form());
    });
    $(document).on('click',"#cr",function(){
        crea_form();
    });

    $(document).on('click',"#title",function(){
        alert("title fired");
    });
    $(document).on('click',"#content",function(){
        alert("content fired");
    });
});

阅读http://api.jquery.com/on

于 2013-06-05T06:54:00.727 回答