可以获取templateInstance值但不能将其用于其他功能吗?

时间:2015-03-11 21:55:28

标签: javascript polymer shadow-dom

我刚刚想出如何从我的一个模板实例中获取一个元素的id并尝试在另一个函数中使用它,但是虽然控制台日志返回正确的ID,但当我尝试使用它们时,在我的.play()函数中,它表示“undefined不是函数”。无论我尝试做什么功能,无论是eventlistener,还是其他任何功能都会发生这种情况!我认为问题与javascript如何看到shadowDOM中的元素有关?我不完全确定。这是我的功能:

//plays an audio file by it's id specified in a repeating template
playAudio: function () {
    var audioId = event.target.templateInstance.model.s.soundId;
    console.log(audioId);
    //^ that is correct in the console log for every ID
    var image = event.target.templateInstance.model.s.imgId;
    console.log(image);
    //^ further tests, this is correct for every img ID
    audioId.play();
    //"undefined is not a function"
}

然后我的重复模板,img元素上有on-click:{{playAudio}}

<template>
    <div layout horizontal wrap center center-justified class="asdf">
        <template repeat="{{s in carddata}}">
            <sound-card>
                <img src="{{s.imgurl}}" id="{{s.imgId}}" on-click="{{playAudio}}">
                <span>{{s.quote}}</span>
                <audio id="{{s.soundId}}" src="{{s.soundurl}}" controls preload="auto"></audio>
            </sound-card>
        </template>
    </div>
</template>

关于javascript如何处理从重复模板中获取的元素,是否有一些我缺少的东西?

1 个答案:

答案 0 :(得分:1)

你不能演奏弦乐。相反,您需要首先获取实际的DOM元素,如下所示:

document.getElementById(audioId).play();
相关问题