通过onclick事件使文本变为粗体

时间:2014-09-02 13:42:08

标签: javascript jquery

我想通过单击按钮使文本变为粗体。看下面的代码,我遇到的问题是我无法将textarea ID传递给boldTF()函数。

<button type="button" id="tfButton">Add text</button>
<div id="InputsWrapper"></div>
<script>
$(document).ready(function() {
    var tfCont = 0;
    var InputsWrapper = $("#InputsWrapper");
    var x = InputsWrapper.length; 
    var namefield = $("#tfButton");

    $(namefield).click(function() {
        tfCont++;
        $(InputsWrapper).append('<div>' + '<div class="name" id="InputsWrapper_0' + tfCont + '">' + '<input type="textarea" id="field_' + tfCont + '" class="fTypex" placeholder="Type Here"/>' + '<br /><button type="button" onclick="boldTF("field_' + tfCont + '")">Bold</button>' + '<br>' + '</div>' + '</div>');
        x++;
        return false;
    });

    function boldTF(tmp){
        document.getElementById(tmp).style.fontWeight = "bold";
        //alert(tmp);
    };
});
</script>

谢谢。

2 个答案:

答案 0 :(得分:1)

很多问题

  1. <input type="textarea"应为<input type="text"<textarea ...></textarea>
  2. 使用课程到达现场
  3. 无需将DOM访问与jQuery混合
  4. jQuery可以使用委托在动态创建的对象上附加事件处理程序。
  5. Working fiddle

    $(function () {
        $("#tfButton").on("click", function(e) {
            e.preventDefault;
            var tfCont = InputsWrapper.length;
            $("#InputsWrapper").append(
                '<div class="name" id="InputsWrapper_0' + tfCont + '">' +
                '<input type="text" id="field_' + tfCont + '" class="fTypex" placeholder="Your first name"/>' +
                '<br /><button type="button" class="boldTF">Bold</button><br /></div>');
        });
        $("#InputsWrapper").on("click", ".boldTF", function(e) {
            e.preventDefault();
            $(this).parent().find(".fTypex").css({"font-weight":"bold"});
        });
    });
    

答案 1 :(得分:0)

删除内联事件处理程序并使用事件委派:

$(document).on('click', 'button', function () {
    $(this).closest('div.name').find('input').css('font-weight', 'bold')
})

<强> jsFiddle example

相关问题