jQuery 1.11.1:append动态创建按钮点击事件无效,求图片缩放方案
Hey there! The problem you're facing is a classic one with dynamically generated elements—your original event binding doesn't work because the #ttt button doesn't exist in the DOM when your binding code runs. Here's how to fix it, plus a complete implementation for your image zoom feature:
Why Your Original Code Fails
When you run $("#ttt").on("click", ...), jQuery looks for the element with ID ttt right then. But since you're creating this button later via the renderModal method, it doesn't exist yet—so the event never gets attached.
Solution: Use Event Delegation
Instead of binding directly to the dynamic button, attach the event to a parent element that exists when your code runs (like document or the modal container itself). This way, the event "bubbles up" to the parent, which can detect clicks on its dynamic children.
Step 1: Update Your Button Rendering
First, give the minus button an ID too (for consistent targeting) and keep your modal structure:
ImagesGridModal.prototype.renderModal = function() { this.$modal = $('<div>', { class: 'imgs-grid-modal' }).append( $('<div>', { class: 'zoom-btn' }).append( $('<button id="zoom-in">', { class: 'zoom-btn' }).append("+") ).append( $('<button id="zoom-out">', { class: 'zoom-btn' }).append("-") ) ).appendTo('body'); }
Step 2: Bind Events with Delegation
Replace your original click binding with this event-delegated code. We'll also add the zoom logic here:
// Use event delegation on a stable parent (document works, but .imgs-grid-modal is more efficient) $(document).on('click', '#zoom-in, #zoom-out', function() { // Get the target image in the modal (adjust the selector to match your image's actual class) const $modalImage = $('.imgs-grid-modal .imgs-grid-modal-img'); if (!$modalImage.length) return; // Get current scale (default to 1 if not set) let currentScale = parseFloat($modalImage.data('scale')) || 1; // Adjust scale based on which button was clicked if ($(this).attr('id') === 'zoom-in') { currentScale = Math.min(currentScale * 1.1, 2); // Cap max zoom at 2x } else { currentScale = Math.max(currentScale * 0.9, 0.5); // Cap min zoom at 0.5x } // Apply the zoom using CSS transform (smoother than resizing width/height) $modalImage.css('transform', `scale(${currentScale})`); // Save the current scale for next clicks $modalImage.data('scale', currentScale); });
Key Notes:
- Target a closer parent: If you can, replace
documentwith.imgs-grid-modal(since that's the parent container you append tobody). This is more performant because the event doesn't have to bubble all the way up to the top of the DOM. - Scale limits: The
Math.minandMath.maxcalls prevent the image from zooming too far in or out—adjust these values to fit your needs. - CSS transform: Using
transform: scale()is better than modifyingwidth/heightbecause it maintains the image's original position and avoids layout shifts.
内容的提问来源于stack exchange,提问作者user2459780

