【问题标题】:JQM: Dynamically created button does nothingJQM:动态创建的按钮什么都不做
【发布时间】:2013-12-27 18:46:22
【问题描述】:

我正在使用 jQuery 和 jQuery Mobile (1.3.2) 创建一个带有 Phonegap 的应用程序。我还没有找到一种方法来让动态创建的按钮工作。我将锚点用作按钮,所以“button('refresh')”什么都不做。

首先我在 HTML 中定义了一个按钮,如下所示:

<a data-role="button" data-icon="plus" data-iconpos="right" id="addNewStep">Add a step</a>

然后我有 Javascript 可以像这样向那个按钮添加一个动作:

$('#addNewStep').click(function (e) {
    e.preventDefault();
    e.stopImmediatePropagation();

    addStepDiv();
});

上面的按钮 WORKS 并创建了一个新的 ul 元素,其中包含一个锚按钮。那个锚按钮是我无法开始工作的那个。这有点乱,因为我有一些样式选项。多行字符串有效,因为显示了整个元素。 addStepDiv():

function addStepDiv() {
    stepDiv = '<ul class="newStepList containerBox" data-role="listview" data-inset="true" data-dividertheme="a"> \
    <li data-role="list-divider" data-dividertheme="a"> \
        <span style="float: left; margin-top: 7px;">Title</span> \
        <a data-role="button" data-mini="true" data-inline="true" data-icon="delete" data-iconpos="notext" class="delStepButton"></a> \
        <br style="clear: both;" /> \
    </li> \
        <li>Text</li> \
    </ul>';

    // Adds the above div under the "Add a step" -button
    $('#addNewStep').parent().append(stepDiv).trigger('create');
}

删除按钮应该做一些事情。现在我已经发出警报,只是为了看看按钮是否工作。不显示任何警报。

$('.delStepButton').click(function (e) {
    e.preventDefault();
    e.stopImmediatePropagation();

    alert("Delete button");
});

其他一切正常。 “添加步骤”按钮创建 ul 元素并正确显示,“删除”按钮也显示,但单击时没有任何反应。

//编辑: 我觉得自己像个白痴……非常感谢您的回答(Sridhar R & JCabello)。 问题已解决:

$(document).on('click', '.delStepButton', function (e) {
    //Do stuff here.
}); 

【问题讨论】:

标签: javascript jquery jquery-mobile button dynamic


【解决方案1】:

由于.delStepButton 元素是动态创建的,您需要使用事件委托将事件处理程序注册到这些元素。

当您使用$('.delStepButton').click(....); 注册事件处理程序时,它将仅将句柄注册到在代码执行时已存在于 dom 中的那些元素,在您的情况下,因为这些元素是在处理程序之后创建的不会附加到新创建的元素上

试试这个

$(document).on('click','.delStepButton',function (e) {
    e.preventDefault();
    e.stopImmediatePropagation();
    alert("Moi");
});

【讨论】:

    【解决方案2】:

    尝试将侦听器附加到文档,而不是项目本身,因为在您放置侦听器时它不存在。

    $(document).on('click', '.delStepButton', function (e) {
        //Do stuff here.
    });
    

    【讨论】:

      猜你喜欢
      • 2016-07-24
      • 1970-01-01
      • 2012-08-30
      • 2018-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-28
      • 2011-09-10
      相关资源
      最近更新 更多