首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何根据wordpress中使用的按钮id获取图像url?

如何根据wordpress中使用的按钮id获取图像url?
EN

Stack Overflow用户
提问于 2014-03-20 03:50:36
回答 1查看 948关注 0票数 0

我的目标是根据我点击的按钮获取图像url,并在适当的输入文本/框上传递url值。另外,我还使用wordpress的媒体库来获取图像。

我有这个html代码:

代码语言:javascript
复制
<label for="upload_image">
  First Slide <br />
   <input id="imageurl-1" type="text" size="36" name="ad_image" value="http://" />
   <input id="1" class="button" type="button" value="Upload Image" />
   <br />Enter a URL or upload an image
</label>

<label for="upload_image">
  Second Slide <br />
   <input id="imageurl-2" type="text" size="36" name="ad_image" value="http://" />
   <input id="2" class="button" type="button" value="Upload Image" />
   <br />Enter a URL or upload an image
</label>

这是基于教程这里的我的脚本。我只是稍微增强了一点,让我可以选择多个图像。

代码语言:javascript
复制
jQuery(document).ready(function($){

    var custom_uploader;

 $('.button').each( function(index) {
    $(this).click(function(e) {

        e.preventDefault();
        var button_id = this.id;
        alert(button_id); //only to know the button id i clicked
        //If the uploader object has already been created, reopen the dialog
        if (custom_uploader) {
            custom_uploader.open();
            return;
        }

        //Extend the wp.media object
        custom_uploader = wp.media.frames.file_frame = wp.media({
            title: 'Choose Image',
            button: {
                text: 'Choose Image'
            },
            multiple: false
        });

        //When a file is selected, grab the URL and set it as the text field's value
        custom_uploader.on('select', function() {
            attachment = custom_uploader.state().get('selection').first().toJSON();
                $('#imageurl-' + button_id).val(attachment.url);
        });

        //Open the uploader dialog
        custom_uploader.open();

    });
 });

});

情况是。当我单击按钮1并选择一个图像时,图像url将填充我的输入文本(id是"imageurl-1"),这是正确的。问题在按钮2上,因为在我选择了一个图像之后,该按钮2中的图像url将替换第一个输入文本上的值(id是"imageurl-1"),该值应该填充在输入文本2上(id是"imageurl-2")。我想我在这部分代码上遇到了困难

$('#imageurl-‘+ button_id).val(attachment.url);

它的button_id也必须“刷新,我认为”每次我点击按钮,以使它完美。希望有人能帮我。

EN

回答 1

Stack Overflow用户

发布于 2014-03-20 11:34:36

我认为对custom_uploader.on('select', function() {上的select事件的回调绑定到button_id值为1的范围内。对所有.button元素进行迭代也是没有意义的,$('.button').click(function(e) {将足够好。

简单的解决方案可能是在使用custom_uploader.off('select')之前先用custom_uploader.on('select', function() {删除以前的回调,这样就可以在每个单击事件上获得新的回调。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22523105

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档