HTML 原生 `
<label for="username">用戶名</label>
<input type="text" id="username">
<script>
$('label').on('click', function(e) {
const targetId = $(this).attr('for');
if (targetId) {
// 觸發原生 click 事件(會冒泡、觸發綁定的處理器)
$('#' + targetId).trigger('click');
// 或僅聚焦:$('#' + targetId).trigger('focus');
}
});
</script>
e.originalEvent 或加標記區分。$(document).on('click', 'label', ...)。document.addEventListener('click', e => {
if (e.target.matches('label[for]')) {
const input = document.getElementById(e.target.htmlFor);
if (input) input.click(); // 或 input.focus()
}
});
優先使用標準 `