如何从jQuery'重新使用元素的ID?事件?

时间:2017-03-13 23:03:43

标签: javascript jquery html

我正在尝试根据特定事件显示特定的HTML。在这种情况下,它是一个按钮单击,然后显示文本和一个或多个按钮选择。进行选择时,显示的HTML文本和按钮由click函数中的嵌入式switch语句确定。使用相同的开关块和" on"重复此过程。事件

我遇到的问题是在jQuery函数中,单击新显示的按钮(例如 - 案例0中的按钮)不会触发该功能,并且切换不会触发。如果我执行追加,我可以单击第一个按钮(函数外部)并且它将连续触发该函数(情况0再次),但是从switch语句中,它不会触发"上"事件

非常感谢任何帮助。

var stepNum = 0;
$('#content').html('<h1>Start</h1><button id="sendButton">Go to case 0</button>');
$('#sendButton').on('click', function () {
switch(stepNum) {
    case 0:
        $('#content').html('<h1>Switch case 0</h1><button id="sendButton">To case 2</button>');
                stepNum = 2; //Next click would go to case 2
        $('#sendButton').off('click');
        refresh()
        break;
    case 1:
        $('#content').html('<h1>Switch case 1</h1><button id="sendButton">To case 0</button>');
                stepNum = 0; //Next click would go to case 0
        break;
    case 2:
        $('#content').html('<h1>Switch case 2</h1><button id="sendButton">To case 1</button>');
                stepNum = 1; //click would go to case 1
        break;            
    default:
        $('#content').append('<h1>Default!</h1>');
                stepNum = 4;
        }
return false;
});

Here's a link to the JS Fiddle.

2 个答案:

答案 0 :(得分:2)

这是因为事件监听器只添加了一次,最初是渲染的元素。

如果要在具有该ID的每个元素上触发它,请尝试

$('body').on('click', '#sendButton', function () {})

选中JSFiddle

答案 1 :(得分:0)

//You can bind the click event to the document passing the reference
//in this case is "#sendButton"

https://jsfiddle.net/06j440k4/1/

相关问题