【问题标题】:How to alter dynamic/live element attributes - (replaceWith()) used如何更改动态/实时元素属性 - (replaceWith()) 使用
【发布时间】:2015-06-22 16:01:34
【问题描述】:

我很难理解如何访问和更改使用 replaceWith 代替占位符元素添加的 HTML 内容的属性。

这是场景:

这是替换后续 HTML 表中的“#null_item”元素的 HTML(保存在 php 文件中):

<tr id="sign_options">
	<td>
		<input class="finalSign" type="hidden" value="" name="item_name_1" />
		<figure class="sample">
			<a id="sign_preview_lightbox" href="" rel="lightbox" title="Sign preview">
				<img id="sign_preview" src="/signs/previews/basic_aluminium_spacer4_f.jpg" alt="Sign preview" title="Sign preview" />
			</a>
		</figure>
	</td>
</tr>

if(localStorage['cartItem']) {
  $.get("/cart.php", function(data) {
    $('#null_item').replaceWith($(data));//fix this 'replaceWith' kak!
  });
}

console.log(signPreview);
console.log(document.getElementById('sign_preview').src);
<table id="quote">
  <colgroup>
    <col id="sign_col" span="1"><col id="options_col" span="1"><col id="qty_col" span="1"><col id="price_col" span="1"><col id="total_col" span="1">
  </colgroup>
  <th>Sign</th><th>Options</th><th>Qty</th><th>Price</th><th>Total</th>

  <tr id="null_item"><td><span class="italic">Empty</span></td><td></td><td></td><td></td><td id="delivery" class="subtotal">S$0</td></tr>
  <tr id="totals"><td></td><td></td><td colspan="2"><span class="boxed">Total signs</span></td><td>S$0</td></tr>
  <tr id="totals"><td></td><td></td><td colspan="2"><span class="boxed">Delivery</span></td><td>S$0</td></tr>
  <tr id="totals"><td></td><td></td><td colspan="2"><span class="boxed">Installation</span></td><td>S$0</td></tr>
  <tr id="discount"><td colspan="2">Discount code <input maxlength="7" class="discountCode" value="" onchange="calculateTotals()" name="discount_code"></td><td colspan="2"><span class="boxed">Discount</span></td><td>-S$0</td></tr>
  <tr id="grand_total"><td></td><td></td><td colspan="2"><span class="boxed">Grand total</span></td><td>S$0</td></tr>
  <tr id="buy_row"><td colspan="4"><img id="secure" src="/img/payment.png" alt="Secure payment via Paypal" title="Secure payment via Paypal"></td><td><input id="buy_now" class="buy_button" type="submit" name="submit" value="BUY NOW" alt="PayPal . The safer, easier way to pay online." onclick="paypalPasser()" /></td></tr>
</table>

第一个 HTML 块成功替换了预期的“#null_item”tr,但之后,我无法替换“#sign_preview”img 的 scr,也无法读取任何现有的 src 链接。

任何人都可以阐明吗?我知道对于事件,必须使用 .on 函数并以新元素为目标,但我不知道如何使用该方法来更改动态加载元素的属性。

【问题讨论】:

  • 附带说明,您的 HTML 标记无效,ID 在文档上下文中必须是唯一的

标签: jquery dynamic replace live


【解决方案1】:

我认为你可能唯一没有想到的是回调和异步方法的想法。

您当前正在运行console.log 语句replaceWith 发生之前。

作为第二个参数传递给$.getfunction() { } 块(您的“回调”)在对服务器的AJAX 调用完成之前不会执行;调用$.get 之后的其余代码将继续立即运行。

试试这个,看看效果:

console.log('About to $.get');
if(localStorage['cartItem']) {
  console.log('$.get()ing...');
  $.get("/cart.php", function(data) {
    $('#null_item').replaceWith($(data));//fix this 'replaceWith' kak!
    console.log('$got!');
    console.log(document.getElementById('sign_preview').src);
  });
}
console.log('After $.get()');

输出将是:

About to $.get
$.get()ing...
After $.get()
...
$got!
<the value of .src>

所以基本上,您试图在元素存在之前访问它。如果你想通过 AJAX 方法运行代码,它应该在回调中,或者从回调中调用。

我会这样重写它:

$.get("/cart.php").done(function(data) { 
    $('#null_item').replaceWith(data);
    // further processing
}).fail(function(xhr, status, message) { 
    // handle failures
    alert('Ouch, an error occurred! ' + message);
});

【讨论】:

    【解决方案2】:

    @Cory,您的评论为我指明了正确的方向,我使用 .get() 的 .done() 回调函数解决了这个问题:

    	if(localStorage['cartItem']) {
    		$.get("/cart.php", function(data) {
    			document.getElementById('null_item').outerHTML = data;
    			//$('#null_item').replaceWith($(data));//fix this 'replaceWith' kak!
    			//$('#null_item').remove();
    		})
    			.done(function() {
    				//Assign cart object key-values to table row elements
    				var parsedCartItem = JSON.parse(localStorage['cartItem2']);
    				var signPreview = parsedCartItem.Sign.Front;
    				
    				console.log(signPreview);
    				console.log(document.getElementById('sign_preview').src);
    				
    				$('#sign_preview_lightbox').attr('href', signPreview);
    				$('#sign_preview').attr('src', signPreview);
    			});
    	}

    【讨论】:

    • 仅供参考,function (data) { ... }.done() 函数都将在 $.get 完成时被调用。我建议将您的 .outerHTML 赋值行移动到 .done() 并完全省略 $.get 的第二个参数。将相同的参数传递给每个,因此您只需将data 参数添加到.done() 中的函数。例如。 $.get("/cart.php").done(function(data) { ... }).fail(function() { /* ouch! */ });
    • 我用代码 sn-p 编辑了我的答案,说明了我的想法。
    猜你喜欢
    • 2011-05-03
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    • 1970-01-01
    • 2014-07-27
    相关资源
    最近更新 更多