JS

2013-07-05 2 views
2

을 통해 IMG 속성을 VAR에서 가져오고 바꾸는 방법 INPUT VAR HTML 에서 SRC, ALT, HEIGHT, WEIGHT와 같은 조건부 IMG 속성을 가져 오는 방법과 IMG 태그 만 영향을받는 대신 자리 교체를 수행하는 방법, 나머지 HTML은 그대로 유지되어야합니다 ...JS

어떻게 js/jquery에서이 작업을 수행 할 수 있습니까?

조건

if images->getAttribute('width') > 18 && images->getAttribute('width')< 640) 

INPUT :

html='<p>some text</p> 
<p><img src="image_1.jpg" width="630" height="380" alt="image_1"></p> 
<p>some more text</p> 
<p><img src="image_2.jpg" width="18" height="18" alt="image_2"></p>'; 

출력 :

html='<p>some text</p> 
<p><a class="test" title="image_1" href="image_1.jpg" rel="image_1"> 
<img width="630" height="380" alt="" src="image1.jpg" ></a></p> 
<p>some more text</p> 
<p><img src="image_2.jpg" alt="image 2" width="18" height="18"></p>'; 
+0

ㅁ 너 지금까지 해봤 니? – dave

+0

Javascript 프로그래밍 방법을 알고 있습니까? 그것은 객체에 대해'->'표기법을 사용하지 않고'.'을 사용합니다. – Barmar

+1

귀하의보기가 질문과 일치하지 않는 것 같습니다. 당신은'IMG' 태그를 수정하고 싶다고 말했고 왜 'A' 태그를 추가 했습니까? – Barmar

답변

1

당신은 그 (사용하여 jQuery를) 할 수있는 :

$html = $(html); 

//For each img in html 
$html.find('img').each(function() { 
    $img = $(this); 

    //Your own logic 
    if ($img->attr('width') > 18 && $img->attr('width') < 640) { 
     //We create our a link 
     $a = $('<a class="test" title="' 
      + $img.attr('title') + '" alt="' 
      + $img.attr('title') + '" href="' 
      + $img.attr('src') + '"></a>'); 

     //We add a cone of the original image into our a 
     $a.append($img.clone()); 
    } 

    //We replace our image by our a link 
    $img.replaceWith($a); 
}); 

//We get the new html string 
html = $html.html();