如何根据wordpress中使用的按钮ID获取图像网址?

时间:2014-03-20 03:50:37

标签: jquery wordpress

我的目标是根据我点击的按钮获取图片网址,并在正确的输入文字/框上传递网址值。我还使用wordpress的媒体库来获取图像。


我有这个HTML代码:

<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>

这是我基于教程here的脚本。我只是增强一点,让我选择多个图像。

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也必须“刷新我认为”。希望有人能帮助我。

1 个答案:

答案 0 :(得分:0)

我认为在线回调选择事件     custom_uploader.on('select', function() { 绑定到button_id的值为1的范围。 迭代所有.button元素也没有意义, $('.button').click(function(e) {就足够了。

简单的解决方案可能是在排除前使用custom_uploader.off('select')删除以前的回调  custom_uploader.on('select', function() {,因此每次点击活动都会收到新的回调。