使用捕获的字段值中的图像更新div

时间:2014-02-09 17:42:52

标签: javascript jquery

我在JS中有一些旧代码,并希望将其转换为使用jQuery。我不是JS程序员,不知道怎么做?

<script type="text/javascript">
function img_show()
{
    piccontainerobj=document.getElementById("pictureareaG")
    piccontainerobj.innerHTML='<img src="image.php/image-name.jpg?width=750&image='+''+document.RecordArticle.article_foto.value+'">'

}
</script>

我有一个ID为idarea的DIV,我的文章foto是一个输入字段。

当页面加载时,我已经在foto字段中有了一些信息,所以我需要显示该图像onload。每次用户在输入字段中输入一些文件名或类型时,每个新字符都会更改字段,以便可以像自动完成一样捕获它吗?

4 个答案:

答案 0 :(得分:1)

  1. 下载并加载jQuery(或使用CDN) - 注意版本2与ie8不兼容
  2. 假设您的文章foto是输入字段,请尝试使用此

  3. 简易版

    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
    function img_show() {
     $("#pictureareaG").html('<img src="image.php/image-name.jpg?width=750&image="+
       $("input[name='article_foto']").val()+'">');
    }
    </script>
    

    使用更改和密钥处理程序

    Live Demo

    function showImage() {
      var val = this.value;
      if (val.length) { // if field has any value
        var src = "image.php/image-name.jpg?width=750&image="+val;
        $("#pictureareaG").html($('<img/>',{src:src}));
      }
    }
    $(function() { // when page loaded
      $("input[name='article_foto']").on({
        "change": showImage, // when the field changed
        "keyup" : showImage // when input
      }).change(); // assign and trigger 
    });
    

    更改

    if (val.length) { // if field has any value
    

    if (["gif","jpg","png"].indexOf(val.split('.').pop())>-1) { //image only
    

    如果你想测试用户是否输入了图片的名称,但由于你在URL的中间有一个点,所以在你的情况下它永远不会是真的

答案 1 :(得分:0)

function img_show()
{
    piccontainerobj = $("#pictureareaG");
    piccontainerobj.html('<img src="image.php/image-name.jpg?width=750&image='+''+document.RecordArticle.article_foto.value+'">')
}

虽然更可读的方式可能是:

function img_show()
{
    var piccontainerobj = $("#pictureareaG"),
        recordArticle = document.RecordArticle.article_foto.value,
        imgSrc= "image.php/image-name.jpg?width=750&image='" + recordArticle + "'",
        newImg = $("<img />",{"src":imgSrc});
    piccontainerobj.html(newImg);
}

这样做可以更容易地在对象文字中指定其他属性。

答案 2 :(得分:0)

在使用之前加载jQuery库

function img_show() {
    piccontainerobj = $('#pictureareaG');
    piccontainerobj.html('<img src="image.php/image-name.jpg?width=750&image=' + '' + $(document.RecordArticle.article_foto).val() + '">');
}

答案 3 :(得分:0)

怎么样

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(function(){
    $('input[name="article_foto"]').change(function(){
       var foto = this.value,
           newElement = $('<img/>',{
                src: 'image.php/image-name.jpg?width=750&image='+foto
            });
       $('#pictureareaG').html(newElement);
    });
});
</script>