jQuery动态添加可排序元素后实现拖拽缩放、获取位置及动态添加表单选项
问题解决指南
1. 动态元素draggable、resizable不生效及位置尺寸保存问题
问题原因
直接对.new_element_class批量绑定交互事件,仅对页面初始加载时已存在的元素生效,后续动态新增的元素未被绑定对应事件,因此功能无法触发。
解决方案
每次创建完新的动态元素后,单独为该元素初始化draggable和resizable能力,在事件回调中直接获取位置、尺寸参数保存即可:
// 新增动态元素逻辑中,新元素创建后赋值为$newEl,执行以下初始化代码 $newEl.draggable({ cursor: "move", stop: function(event, ui) { // 存储元素位置尺寸,可根据需求存入元素属性、本地存储或后端接口 const attr = { left: Math.floor(ui.position.left), top: Math.floor(ui.position.top), width: Math.floor($(this).width()), height: Math.floor($(this).height()) }; $(this).data('elementAttr', attr); $('#for_drag').html('拖动结束! left : ' + attr.left + ' Top : ' + attr.top); } }).resizable({ handles : "n,s,w,e,ne,se,sw,nw", minWidth : 215, minHeight : 30, helper: "ui-resizable-helper", animate: true, stop: function(event, ui) { const attr = { left: Math.floor($(this).offset().left), top: Math.floor($(this).offset().top), width: Math.floor(ui.size.width), height: Math.floor(ui.size.height) }; $(this).data('elementAttr', attr); $('#for_resize').html('调整大小结束! Width : ' + attr.width + ' Height : ' + attr.height); } });
2. 动态添加选项总是追加到首个元素的问题
问题原因
使用全局变量存储select和按钮的ID,新增元素时全局变量会被覆盖,事件回调中引用的始终是最新的ID值,导致选项始终追加到匹配的首个元素;同时废弃的live方法反复绑定事件也会造成逻辑混乱。
解决方案
使用事件委托绑定交互,避免依赖全局变量,每次触发事件时从当前元素提取标识,匹配对应的目标元素:
jQuery修正代码
// 全局绑定一次事件委托即可,无需每次新增元素重复绑定 $(document).on('click', '[id^="option_adder"]', function() { // 从当前点击的按钮ID提取随机标识,匹配对应select const randNo = this.id.replace('option_adder', ''); const $targetSelect = $(`#select_name_${randNo}`); if (!$targetSelect.length) return; $targetSelect.append('<option value="whatever">text</option>').val('whatever'); });
原生JS修正代码
function dataadder(optionId) { // 动态获取对应select,不依赖全局变量 const randNo = optionId.replace('option_adder', ''); const targetSelect = document.getElementById(`select_name_${randNo}`); if (!targetSelect) return; // 计数存储在当前select属性上,避免多个元素共用全局计数 let count = +targetSelect.dataset.optionCount || 0; count++; targetSelect.dataset.optionCount = count; const opt = document.createElement('option'); opt.value = 'data is ' + count; opt.innerHTML = 'data is ' + count; targetSelect.appendChild(opt); }
内容的提问来源于stack exchange,提问作者Aunsu Chandra
相关产品推荐
相关产品推荐

