2014-02-28 56 views
0

我在我的頁面bootstrap Dropdown component獲得所選元素

<div class="btn-group"> 
    <button class="btn dropdown-toggle" data-toggle="dropdown" title="Police"><i class="fa fa-font"></i>&nbsp;<b class="caret"></b></button> 
    <ul class="dropdown-menu" id="fonts"></ul> 
</div> 

而且我使用這個腳本填補這一Dropdown component

var fonts = [ 
    'Serif', 
    'Sans', 
    'Arial', 
    'Arial Black', 
    'Courier', 
    'Courier New', 
    'Comic Sans MS', 
    'Helvetica', 
    'Impact', 
    'Lucida Grande', 
    'Lucida Sans', 
    'Tahoma', 
    'Times', 
    'Times New Roman', 
    'Verdana' 
]; 

var fontsDropDown = document.getElementById('fonts'); 
fonts.forEach(function(police){ 
    var li = document.createElement('li'); 
    var a = document.createElement('a'); 
    a.style = "font-family:'" + police + "'"; 
    a.appendChild(document.createTextNode(police)); 
    li.appendChild(a); 
    fontsDropDown.appendChild(li); 
}); 

而且我有一個可編輯div

<div id="editor" contentEditable="true"> Enter your text here.. </div> 

我想要當我選擇一些元素在Dropdown component變更爲可編輯的div所選文本的字體,我試圖在<ul>添加事件監聽每個<a>Dropdown component

var fontsArray = Array.prototype.slice.call(document.querySelectorAll('#fonts li a')); 
fontsArray.forEach(function(value){ 
    value.addEventListener('click', function(){ 
     document.execCommand('fontName', false, value); 
    }, false); 
}); 

,但它不工作,我想上的按鈕測試document.execCommand('fontName', false, value);Dropdown component直接爲以下幾點:

document.getElementById('fonts').addEventListener('click', function(){ 
     document.execCommand('fontName', false, 'Comic Sans MS'); 
    }, false); 

和它的作品,所以我想我只需要得到對Dropdown component「選定的元素值,併爲document.execCommand()第三個參數替換它。

我累了,以搜索做腳本,和所有我能找到的是使用jQuery:

$(function(){ 

    $(".dropdown-menu li a").click(function(){ 

     $(".btn:first-child").text($(this).text()); 
     $(".btn:first-child").val($(this).text()); 

    }); 

}); 

但我想用純JavaScript來獲得所選擇的項目。

我該怎麼做?

回答

0

嘿Aimad我相信這將做修正:

var fontsArray = document.getElementById('fonts').getElementsByTagName('a'); 
var l = fontsArray.length; 
for(i = 0; i<l; i++){ 
    tag = fontsArray[i]; 
    tag.addEventListener('click', function(){ 
    var value = this.innerHTML; 
    document.execCommand('fontName', false, value); 
    }, false); 
}; 

你需要var value = this.innerHTML;重新定義價值能夠訪問字體的名稱。

希望有所幫助。

乾杯