【问题标题】:Can get templateInstance value but can't use it for another function?可以获取 templateInstance 值但不能将其用于其他功能?
【发布时间】:2015-03-11 21:55:28
【问题描述】:

我最近才弄清楚如何从我的一个模板实例中获取元素的 ID,并尝试在另一个函数中使用它,但是尽管控制台日志返回正确的 ID,但当我尝试使用它们时,例如在我的.play() 函数中,它说“未定义不是函数”。无论我尝试执行什么功能,无论是事件监听器还是其他任何功能,都会发生这种情况!我认为问题可能与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 如何处理我从重复模板中获得的元素,我有什么遗漏吗?

【问题讨论】:

    标签: javascript polymer shadow-dom


    【解决方案1】:

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

    document.getElementById(audioId).play();
    

    【讨论】:

    • 谢谢!现在效果很好:-)
    猜你喜欢
    • 1970-01-01
    • 2011-12-16
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    • 2015-01-06
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多