2016-04-01 19 views
0

aşağıdaki görev var - Böyle bir şey yoktur yani eğer (src hariç tüm özelliklere sahip) komut nesnesinin bir kopyasını oluşturmak gerekir:Yerel JS'yi kullanarak bir komut dosyasının tam kopyası nasıl oluşturulur?

<script src="1" async data-x="bb"> 

bazı komut dosyası etiketi oluşturmak ve eklemek gerekir

var script = document.currentScript; 

insert('new_src', script.attributes); 

function insert(src, attributes) { 
    var script = document.createElement('script'); 
    script.attributes = attributes; 
    script.src = src; 

    oldScript.parentNode.insertBefore(script, oldScript.nextSibling); 
} 

Yeni komut takıldı ancak boş olan: aynı özelliklere sahip, bir tane aşağıdakileri yapmak için denedim

<script src="new_src" async data-x="bb"> 

yani src hariç özellikler. Bunu nasıl yapabilirim? Şimdiden teşekkürler! Sadece başka bir öğeden attributes depolamak için doğal JS

+0

'script.attributes = öznitelikleri;'? o nedir? –

+2

'script.outerHTML'? https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML – Slavik

+0

@Slavik - Bana kodu ver – malcoauri

cevap

1

bir yaklaşım kullanarak, sizin insert fonksiyonu olarak yeniden yazılabilir önüne aldığımızda cloneNode

var newScript = document.currentScript.cloneNode(); 
// newScript has the same attributes as, document.currentScript 
// now you can overwrite the src attribute, 
newScript.src = "new_src"; 

yoluyla elde edilebilir

function insert(src, node) { 
    var script = node.cloneNode(); 
    script.src = src; 
    node.parentNode.insertBefore(script, node.nextSibling); 
} 

Aşağıdaki geliştiriciler araçlarımda test ettiğim aşağıdaki

# grabbed the first <script> tag on the page for brevity, 
> insert("whatever",$$("script")[0]) 

# lets view the <script> tag we cloned from, 
> $$("script")[0] 
# returns, <script type=​"text/​javascript" async src=​"http:​/​/​engine.adzerk.net/​ados?t=1459514526146&request=...,"IsAsync":​true}​">​</script>​ 

# check the attributes on the cloned element, 
> $$("script")[0].nextSibling 
# returns, <script type=​"text/​javascript" async src=​"whatever">​</script>​ 
İlgili konular