2017-03-02 48 views
0

我尝试使用下面的代码时,得到一个选项的属性值属性:

$('#select3,#select5,#select7,#select9,#select11') 
    .children('option[value="'+ selectedDValue +'"]', this) 
    .attr({'disabled': true,'data-subtext':$(this).attr("data-subtext") + ' 
    (postcode area saved in another zone)'}); 

但是$(this).attr("data-subtext")将返回“未定义”,因此该属性是打印为data-subtext="Undefined (postcode area saved in another zone)"。该选项有一个名为data-subtext的属性,所以我想知道为什么没有返回?

+0

创建拨弄链接,这样我们可以来了解确切的问题。或尝试像这样:-' $('#select3,#select5,#select7,#select9,#select11')。children('option [value =''+ selectedDValue +'“]')。each(function() {(disabled):true,'data-subtext':$(this).attr(“data-subtext”)+'(保存在另一个区域的邮编区域)'}); });' –

+0

不幸的是仍然返回undefined @Anant,但感谢尝试 –

回答

1

根据当前代码this指的是window对象不是option因此其返回undefined

您需要使用.attr(attributeName, fn)并从.children()中删除方法。

$(selector).children('option[value="' + selectedDValue + '"]').attr('data-subtext', function(index, value) { 
 
    return value + ' (postcode area saved in another zone)' 
 
});

+0

完美谢谢Satpal和非常有用的解释。立即投入5分钟! –