jQuery数据属性不工作

jQuery数据属性不工作,jquery,custom-data-attribute,Jquery,Custom Data Attribute,我有以下代码: Html <div id="Test" class="test">test</div> <div id="Test1" class="test">test</div> <div data-id="Test2" class="test">test</div> <br /> <div id="result1"></div> <div id="result2"><

我有以下代码:

Html

<div id="Test" class="test">test</div>
<div id="Test1" class="test">test</div>
<div data-id="Test2" class="test">test</div>
<br />
<div id="result1"></div>
<div id="result2"></div>
对于这两个结果div,我希望它们的内容是
Result1:Test.Test1.Test2.
Result2:Test.Test1.Test2.

然而,第一个result div的内容是
Result1:Test.Test1..

为什么会这样


问题在于第三个元素,即使
id
属性不存在
此.id
不是
未定义的
它是一个空字符串。因此,对于第三个元素
test1
获取一个空字符串作为值,但是对于
test2
而言,以下
if
条件使用
id
数据值更新值

一种可能的解决方案是测试
id
属性的长度,而不是检查它是否已定义

var result1 = 'Result1:',
    result2 = 'Result2:';
$('.test').each(function () {
    var test = $(this),
        testId1 = ($.trim(this.id || '').length ? this.id : test.data('id')),
        testId2 = (this.id !== undefined ? this.id : '');

    if (testId2 == '') {
        testId2 = test.data('id');
    }

    result1 += testId1 + '.';
    result2 += testId2 + '.';
});

$('#result1').html(result1);
$('#result2').html(result2);

演示:

您的错误是html代码,id=“Test2”需要id标记而不是data id=“Test2”

测试
测试
测试

这将为您提供您想要的输出。

试试这个

var result1 = 'Result1:',
    result2 = 'Result2:';
$('.test').each(function () {
    var test = $(this),
        testId1 = (test.attr('id')!=undefined ? test.attr('id') : test.data('id')),
        testId2 = (test.attr('id')!=undefined ? test.attr('id') : '');
    if (testId2 == '') {
        testId2 = test.data('id');
    }
    result1 += testId1 + '.';
    result2 += testId2 + '.';
});

$('#result1').html(result1);
$('#result2').html(result2);
拨弄

修改此行

<div data-id="Test2" class="test">test</div> to

<div id="Test2" class="test">test</div>
测试到
测试

问题是因为此.id的
类型
是一个
字符串
,即使它没有设置值

因此,this.id!==“undefined”
始终为true,因此这两个字段始终只有
此.id
作为值

您只需通过以下方式进行尝试:

var test = $(this),
    testId1 = (this.id !== "" ? this.id : test.data('id')),
    testId2 = (this.id !== "" ? this.id : '');

如果元素没有id,element.id将返回一个未定义的空字符串

可以修复并简化:

 var testId1 = this.id ? this.id : test.data('id');

测井
typeof(this.id)
产生3倍的字符串……即使在第三个div中显然没有这些id。Weird@Sarcastic
.data(id)
是否正确检查-->他想让它看到没有id,而是获取数据(“id”),不要重写html。谢谢,我一直在为这个问题挠头,想知道为什么它不起作用-似乎很愚蠢,它总是被定义的,即使它不存在-或者这是js元素的默认构造函数的一部分?非常好,我喜欢这样做的简洁方式谢谢。实际上@Joe的答案更短:
var testId1=this.id | | test.data('id')加上此模式非常容易允许2个以上的可能值,只需继续:
var testId1=this.id | | test.data('id')| | test.data('default')| | blop'
var test = $(this),
    testId1 = (this.id !== "" ? this.id : test.data('id')),
    testId2 = (this.id !== "" ? this.id : '');
 var testId1 = this.id ? this.id : test.data('id');