0
我想遍歷列表項目onload
並檢測他們是否擁有YouTube網址並使用來自iframe中網址的視頻ID。這是我到目前爲止已經完成,但它不工作:如何使用JS驗證YouTube網址
$('li').each(function() {
var url = $(this).text();
if (url != undefined || url != '') {
var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=)([^#\&\?]*).*/;
var match = url.match(regExp);
if (match && match[2].length == 11) {
// Do anything for being valid
// if need to change the url to embed url then use below line
$(this).find('.videoObject').attr('src', 'https://www.youtube.com/embed/' + match[2] + '?autoplay=0&enablejsapi=1').show();
} else {
// Do anything for not being valid
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
foo
<iframe class="videoObject" src=""></iframe>
</li>
<li>
bar
<iframe class="videoObject" src=""></iframe>
</li>
<li>
foo https://www.youtube.com/watch?v=Vr3ya_uPmxg
<iframe class="videoObject" src=""></iframe>
</li>
</ul>
我用我[一些谷歌(http://stackoverflow.com/questions/2964678/jquery-youtube-url-validation-with-regex) – evolutionxbox
是否有問題與您的代碼? –
可能重複[jQuery的YouTube網址驗證與正則表達式](http://stackoverflow.com/questions/2964678/jquery-youtube-url-validation-with-regex) – evolutionxbox