在同一标签中显示图像或swf [英] Display image or swf in same tag

查看:82
本文介绍了在同一标签中显示图像或swf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网页通过AJAX调用从XML获取内容。我从该XML中检索一个URL并使用它在页面上创建一个元素。

My webpage gets the content from XML via an AJAX call. I retrieve a URL from that XML and use it to create an element on the page.

但该URL可能如下所示:

But that URL can look like:


  • http://something/something.jpg

  • http://something/something.swf

  • http://something/something.jpg,
  • or http://something/something.swf

这意味着它可以是图像文件或者可以是.swf文件,因此我无法在同一标签中显示该图像或.swf文件(也是动态创建的)。

This means it can be a image file or can be a .swf file, so I am unable to display that image or .swf file in same tag (which is also created dynamically).

我不知道知道如何在同一标签中显示图像和.swf文件。我该如何解决这个问题?

I don't know how to display both image and .swf file in same tag. How can I solve this?

推荐答案

为什么不在创建标签之前检查URL?您可以使用正则表达式,如下所示:

Why don't you check the URL before creating the tag? You could use a regular expression, like so:

var url     = 'http://something/something.swf';
var matches = url.match(/(swf|jpg)$/i);

if (matches.length > 0) {
    var type = matches[0].toLowerCase();
    /* create the img or embed tag, based on `type` */
}

正则表达式中的 i 使其匹配,无论大小写如何(因此它将匹配something.SWF)和 toLowerCase 确保我们可以将它与小写字符串进行比较(例如 if(type ==='swf'){} )。

The i in the regular expression makes it match regardless of case (so it will match "something.SWF" as well) and toLowerCase makes sure we can compare it to a lowercase string (e.g. if (type === 'swf') { }).

现在您可以使用结果创建正确的标记,如下所示:

Now you can use the result to create the correct tag, like this:

var url     = /* extracted from XML, e.g.: */ 'http://something/something.swf';
var matches = url.match(/(swf|jpg)$/i);

if (matches.length > 0) {
    var type = matches[0].toLowerCase();
    var tag;

    // Create the correct tag:
    if (type === 'swf') { 
        tag = $('<embed type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" />');
    }
    else if (type === 'jpg') {
        tag = $('<img />');
    }

    // Set the src and append to <body>:
    if (tag !== undefined) {
        tag.attr('src', url);
        tag.appendTo('body');
    }
}

请注意,此示例未经测试。例如,您可能需要将< embed> ; tag。

Please keep in mind that this example is untested. For example, you probably need to set the height and width attributed on the <embed> tag.

注意: match 返回一个包含整个匹配的数组,以及任何匹配组。在这种情况下,数组将如下所示: ['jpg','jpg'] 。那是因为该组,(jpg | swf),它们被保存以及完全匹配。如果您需要阻止此行为,可以使用非捕获组,如下所示:(?:jpg | swf),因此不会记住该组。

NB: match returns an array which contains the entire match, plus any matched groups. In this case, the array will look like this: ['jpg', 'jpg']. That's because the group, (jpg|swf), which is saved as well as the complete match. If you need to prevent this behaviour, you can use a non-capturing group, like this: (?:jpg|swf), so the group won't be remembered.

这篇关于在同一标签中显示图像或swf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆