2016-10-26 5 views
0

私は< p>要素の中にいくつかのテキストがあり、ダブルタップされた単語を見つける必要があります。ダブルタップの単語をどのように取得できますか?

イベントを検出するのに効果的なダブルタップjqueryプラグイン(https://gist.github.com/attenzione/7098476)を使用していますが、その下にある単語を取得する方法がわかりません。

どうすれば入手できますか?


私がこれまで持っているものを追加しました:

$("p").on('doubletap',function(event){ 
alert ("double tap"); // event is working 
var sel = (document.selection && document.selection.createRange().text) || (window.getSelection && window.getSelection().toString()); 
alert ("sel "+sel); //<-- not working 
}); 
+0

これまでの投稿を投稿できますか? –

答えて

0

あなただけが上のタップダブルワードを取得したい場合は、各単語の周りspanタグを使用する必要があります。ダブルタップイベントリスナーをp > spanに追加すると、$(clickedElement).text();を使って単語を取得できます。

EDIT:フィドルに与えられたコードに基づいて、サンプルコード を追加します。

$(document).ready(function() { 
    var words = $("#yourTextContainer").text().split(' '); 
    $("#yourTextContainer").html(""); 

    $.each(words, function(i,val) { 
     // wrap each word in a span tag 
     $('<span/>').text(val +" ").appendTo("#yourTextContainer"); 
    }); 

    $("#yourTextContainer span").dblclick(function(event) { 
     var res = $(this).text(); 
     console.log ("sel "+res); 
    }); 
}); 
0

シングルクリックで単語を選択するための1つの同様の質問があります。 Use the mouse to select only one word in text jquery

クリックしたから、このようなdbclickにイベントを変更することができます。 http://jsfiddle.net/tejashsoni111/EHCN6/92/

$(document).ready(function() 
{ 
    var words = $("#yourTextContainer").text().split(' '); 
    $("#yourTextContainer").html(""); 

    $.each(words, function (i, val) 
    { 
     //wrap each word in a span tag 
     $('<span/>').text(val + " ").appendTo("#yourTextContainer"); 
    }); 

    $("#yourTextContainer span").live("dbclick", function (event) 
    { 
     event.stopPropagation(); 
     SelectText($(this)); 
    }); 
}); 

function SelectText(element) 
{ 
    var doc = document, 
      text = element.get(0), 
      range, 
      selection; 
    if (doc.body.createTextRange) 
    { 
     range = document.body.createTextRange(); 
     range.moveToElementText(text); 
     range.select(); 
    } 
    else if (window.getSelection) 
    { 
     selection = window.getSelection(); 
     range = document.createRange(); 
     range.selectNodeContents(text); 
     selection.removeAllRanges(); 
     selection.addRange(range); 
    } 
} 

を更新

選択したテキストを返さ。 更新されたフィドルを確認してください:https://jsfiddle.net/tejashsoni111/mzx6zL65/2/

+0

残念ながら私はデスクトップ上でこの1つの作業を行うことさえできません。 (結果としてundeifnedになる、sel = SelectText($(this));) – fran35

+0

質問を更新し、どのように使用するのかをコードで表示できますか? – tejashsoni111

+0

ありがとうございます。フィドルはhttps://jsfiddle.net/mzx6zL65/ – fran35

関連する問題