gpt4 book ai didi

javascript - 使用jquery向表添加动态href

转载 作者:行者123 更新时间:2023-11-28 02:15:11 25 4
gpt4 key购买 nike

我有一个带有用于插入行的模板的表,我想让这些行可单击,以便我可以编辑它们。如何将 href 值附加到模板?

我的模板

        <tr class="template" style="display:none;">
<td><span class="item_num"> Num </span></td>
<td><span class="item_desc"> Description </span></td>
<td><span class="item_price"> Price </span></td>
<td><span class="item_ref">ref</span></td>
</tr>

我的Javascript

    var newRow = $('#quote .template').clone().removeClass('template');
var quoteItem = {
number: 1,
description: myDescriptionVariable,
price: myPriceVariable,
};


template(newRow, quoteItem)
.insertAfter('#quote tr.template')
.fadeIn()


function template(row, quoteItem) {
row.find('.item_num').text(quoteItem.number);
row.find('.item_desc').text(quoteItem.description);
row.find('.item_price').text(quoteItem.price);
row.find('.item_ref').attr('href','hello');
return row;
}

最佳答案

您可以使用.data()

 row.find('.item_ref').data('ref','hello');

 <span class="item_ref" data-ref="" > Edit</span>

然后你可以像这样使用它 -

     console.log($('.item-ref').data('ref'));

如果您只是希望以某种方式存储数据,那么这可能很有用。如果您还想做点什么,请告诉我。或者 href 保存什么样的数据以及您希望如何进一步使用它。

<小时/>

更新

据我所知,到目前为止,您想要动态添加插入后需要可编辑的行。每行包含一些具有特定值的字段。并且您想将 ref 保存在 item_ref 类中。

所以你可以这样做 -

var num = 1; 
var myDescriptionVariable = 111;
var myPriceVariable = 999;

// You may have some other element triggers cloning
$("button").click(function(){
var newRow = $('#quote .template').clone().removeClass('template');

var quoteItem = {
number: num,
description: 'Description ' + myDescriptionVariable, // added to distinguish items
price: myPriceVariable + ' USD', // added to distinguish items
linkToPopup: myDescriptionVariable + '_link_goes_here' // added to distinguish items
};

template(newRow, quoteItem)
.insertAfter('#quote tr.template')
.show();
});

function template(row, quoteItem) {
row.find('.item_num').text(quoteItem.number);
row.find('.item_desc').text(quoteItem.description);
row.find('.item_price').text(quoteItem.price);
// here 'href' will hold desired link_to_popup
row.find('.item_ref').data('href',quoteItem.linkToPopup);
myDescriptionVariable+= 1; // added to distinguish items
myPriceVariable+=2; // added to distinguish items
num+=1; // added to distinguish items
return row;
}

$("#quote").on("click", ".item_ref",function(){
// this will give to desired link_to_pop_val
alert($(this).data('href'));
});

我添加了一个按钮来进行演示。这种方法绝对避免了不必要的 DOM 元素,例如为每行添加隐藏输入。使用 .data() 您可以为每个字段提供相同的多种信息,例如 -

 $("span").data('key_1', value_1);
$("span").data('key_2', value_2);
$("span").data('key_2', value_3);

fiddle for demonstration

我认为这就是您想做的事情并且应该达到目的。 :)

关于javascript - 使用jquery向表添加动态href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16498781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com