2017-10-04 1 views
0

내가 유효한 HTML로 작성된 속성의 문자열을 가지고, 나는 실제 HTML 요소 (안 요소의 HTML 문자열)에 이러한 속성을 넣어하려는 속성을.html로 요소

예를 들어, 변수 이름이 attributesStr 인 민감한 문자열이 있는데이 속성을 #htmlElement div에 추가하려고합니다.

<div id="htmlElement" class='regularClass' title='Title... with spaces!' style='color: red; font-weight: bold;' data-attributenovalue> 
    The HTML element! 
</div> 

이 어떻게 자바 스크립트 또는 jQuery를이 작업을 수행 할 수 있습니다처럼

JQuery와/자바 스크립트 코드가 실행 된 후

var attributesStr = ""; 
 
attributesStr += " class='regularClass'"; // Needs to handle key value attributes. 
 
attributesStr += " title='Title... with spaces!'"; // And attributes with spaces. 
 
attributesStr += " style='color: red; font-weight: bold;'"; // And style with multiple properties. 
 
attributesStr += " data-attributenovalue"; // And attributes with no value. 
 

 
// Your special code to add the attributes to `#htmlElement` goes here.
<div id="htmlElement"> 
 
    The HTML element! 
 
</div>

, #htmlElement이 보일 것입니다?


첫 번째 시도 : 나는 공간에 attributesStr을 보내고 .split()으로 내가 이것을 할 수있는 생각하고 =에 각각의 속성 키 값 쌍을 분할하고, 한 후 반복하는 그 배열과 각 키 값 쌍을 추가하는 jQuery의 .prop() 또는 .attr()하지만,이 두 가지 이유로 작동하지 않을 것이다 : 그들은 공간을 가지고 있기 때문에

  1. 그것은 styletitle 속성에 실패합니다.
  2. 일 수도 있습니다.은 값이없는 속성에서 작동하지 않습니다.
+0

'attributesStr.match (/ [^ \ S =] + (= '] [^'] *는 '])?/g)'이렇게하면 첫 번째 분할 얻을 – tallberg

+3

미리 만들어진 문자열을 해킹하여 필요한 것보다 더 어렵게 만듭니다. 해당 문자열을 작성한 시점에 스타일을 적용 할 수 있습니까? 또는 나중에 적용 할 값이있는 객체를 만들 수도 있습니다. –

+0

@RoryMcCrossan 이미 원래의 문제에 대한 다른 해결책을 찾았습니다. JS/JQuery에서이 작업을 수행 할 수있는 방법이 있는지 궁금했습니다. –

답변

4

attributesStr을 가지고 삽입

$(document).ready(function(){ 
 
$("#htmlElement").attr("class", "regularClass"); 
 
$("#htmlElement").attr("title", "Title... with spaces!"); 
 
$("#htmlElement").attr("style", "color: red; font-weight: bold"); 
 
$("#htmlElement").attr("data-attributenovalue",true); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="htmlElement"> 
 
    The HTML element! 
 
</div>

click here for attr() usage

. 이를 위해 기존 태그를 제거하고 문자열을 삽입 한 다음 나머지 HTML을 되돌려 노드를 재구성해야합니다.어쩌면

var dummHTML = $("<div "+attributesStr+"></div>"); 
$.each(dummHTML[0].attributes, function(i,v){ 
$('#htmlElement').attr(v.nodeName,v.nodeValue); 
}); 
+0

와우! 그것은 실제로 작동하지만, 만약 당신이 요소를 검사한다면 당신은 이전의'# htmlElement' 안에 새로운 요소를 추가한다는 것을 알게 될 것입니다. 그것을 해결하기 위해 'outerHtml'을 뒤범벅하십시오. –

+1

예, 바보 같은 jQuery의'html()'. 그것을 전혀 사용하지 않을 수도있다. –

0
하여 문자열을 분리하지 왜

','

var attributesStr = ""; 
 
attributesStr = attributesStr + " class='regularClass'," ; // Needs to handle key value attributes. 
 
attributesStr = attributesStr +" title='Title... with spaces!',"; // And attributes with spaces. 
 
attributesStr = attributesStr +" style='color: red; font-weight: bold;',"; // And style with multiple properties. 
 
attributesStr = attributesStr +" data-attributenovalue,"; // And attributes with no value. 
 

 
var array = attributesStr.split(','); 
 

 
array.forEach(function(item){ 
 
property = item.split('='); 
 
$('#htmlElement').attr(property[0].trim()); 
 
if(property[1]) $('#htmlElement').attr(property[0].trim(), property[1].trim()); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="htmlElement"> 
 
    The HTML element! 
 
</div>

+0

모든 속성과 함께 문자열을 사용해야하므로 절대 해당 문자열의 소스 형식을 수정할 수 없습니다. 나는 그 문자열이 어떻게 생겼는지에 대한 예로서'attributesStr' 변수를 포함 시켰습니다. –

0

이 당신에게 첫 번째 분할을 얻을 것이다

attributesStr.match(/[^\s=]+(=['][^']*['])?/g) 

결과 :

["class='regularClass'", "title='Title... with spaces!'", "style='color: red; font-weight: bold;'", "data-attributenovalue"] 

그런 다음 foreach에서 제안한대로 attrs를 처리 할 수 ​​있습니다.

+0

그래, 작동하는 것처럼 보입니다. attrs를 처리하기 위해 나머지 코드를 포함 할 수 있습니까? 그렇다면 틀림없이 작동 할 것입니다. –

1

.attr()을 jquery에서 사용할 수 있습니다. 다음은 작동중인 스 니펫입니다. 기존 outerHTML

+0

모든 속성과 함께 문자열을 사용해야하므로 절대 해당 문자열의 소스 형식을 수정할 수 없습니다. 나는 그 문자열이 어떻게 생겼는지에 대한 예로서'attributesStr' 변수를 포함 시켰습니다. –

+0

문자열을 attr right를 사용하여 별도로 추가하는 대신 모든 속성과 함께 사용 하시겠습니까? –

+0

예, 맞습니다. @rahulpatel –

1

이 시도 아이디어는

을 :의 내용을 요소를 제거한 다음 제거하고 새 속성을 사용하여 다시 만듭니다.

,

var attributesStr = ""; 
 
attributesStr += " class='regularClass'"; // Needs to handle key value attributes. 
 
attributesStr += " title='Title... with spaces!'"; // And attributes with spaces. 
 
attributesStr += " style='color: red; font-weight: bold;'"; // And style with multiple properties. 
 
attributesStr += " data-attributenovalue"; // And attributes with no value. 
 

 
// Your special code to add the attributes to `#htmlElement` goes here. 
 
var $innerHTML = $("#htmlElement").html() 
 
$("#htmlElement").remove() 
 
var $newElement = "<div id='htmlElement' " + attributesStr + ">" + $innerHTML + "</div>" 
 

 
$("body").after($newElement)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="htmlElement"> 
 
    The HTML element! 
 
</div>

1

하지 최선의 선택하지만 전체 문자열을 사용하는 데 필요한 경우 :

var attributesStr = ""; 
 
attributesStr += " class='regularClass'"; // Needs to handle key value attributes. 
 
attributesStr += " title='Title... with spaces!'"; // And attributes with spaces. 
 
attributesStr += " style='color: red; font-weight: bold;'"; // And style with multiple properties. 
 
attributesStr += " data-attributenovalue"; // And attributes with no value. 
 

 
var element = document.getElementById('htmlElement'); 
 

 
var tag = element.tagName; 
 

 
element.outerHTML = '<' + tag + attributesStr + element.outerHTML.substring(tag.length + 1);
<div id="htmlElement"> 
 
    The HTML element! 
 
</div>

관련 문제