我在变量variantId = $(this).prop('id')
中存储了一个Id,并注意到Jquery的两个不同行为:当我改变<td>
的prop
- jquery识别存储在变量中的元素,尽管它被存储为字符串
let variantId;
$(document).on('click', ".tbl-itemClass", function () {
variantId = $(this).prop('id');
$(variantId).prop('contenteditable', true);//changed the prop
}).
但是当我试图获得<td>
中嵌套的<span>
的值时,使用.text()
,当添加'#'
时,jquery只识别存储在变量中的元素
on('input', function () {
let newItemName = $('#' + variantId).find('span.item-description').text();
//let newItemName = $(variantId).find('span.item-description').text(); //this line returned an empty string instead of the <span>s value.
})
这是完整代码:
let variantId;
$(document).on('click', ".tbl-itemClass", function () {
variantId = $(this).prop('id');
$(variantId).prop('contenteditable', true);
}).
on('input', function () {
let newItemName = $('#' + variantId).find('span.item-description').text();
//let newItemName = $(variantId).find('span.item-description').text();
});
这是我的。cshtml(不要认为这有什么区别,我用的是razor page, Asp.Net)
<tbody>
@foreach (var item in Model)
{
<tr currentitemid=" @item.Id">
<td class="tbl-itemClass desc" id="@("description"+ item.Id)" varianttype="@ViewBag.VariantType" >
<span class="spnSpc"> </span>
<span style="width:90%; padding:1px 5px 1px 2px;" **class="item-description"** contenteditable> @item.Description </span>
</td>
<td class="tbl-itemClass ">//more code here
</td>
</tr>
}
你能解释一下的区别吗好吗?谢谢!
在jQuery中,如果你想按ID选择属性,你需要输入:
$('#yourId')...
当你得到variantId作为id存储和使用时,要访问元素。text()你需要#作为id选择器。
这个问题的答案是这一行
$(variantId).prop('contenteditable', true);//changed the prop
不工作,你可能会误认为它有效的原因是因为它在html元素中有contenteditable
属性。