2014-01-09 77 views
2

在ClojureScript中使用dommy,如何通过属性选择节点?例如,在jQuery中,这看起来像$('tr[data-id=1]')。我试图(sel1 "tr[data-id=1]")但我得到这个错误:通过属性选择HTML节点dommy

Uncaught SyntaxError: Failed to execute query: 'tr[data-id=1]' is not a valid selector.

这可能与dommy?如果不是,ClojureScript中最好的选择是什么? jayq?

样本HTML:

<table> 
    <tr data-id="1"> 
    <td>Cow</td> 
    <td>Moo</td> 
    </tr> 
</table> 
+0

你可以在这里发布你的html部分吗? –

+0

@KrishR添加了示例HTML。 –

+0

如果你已经为你的问题得到了答案,那么标记正确的答案总是善意的,即使它是你的;) – yonki

回答

3

Dommy使用document.querySelectorAll引擎盖,这需要属性在选择值加引号下。

(sel1 "tr[data-id='1']") 

如果你不想使用引号,至少有两个简单的选择:

goog.dom.query已经可以在ClojureScript的依赖和支持属性选择。

(ns example 
    (:require [goog.dom.query :as query])) 

(query "tr[data-id=1]") 

jayq是jQuery的包装。将[jayq "2.5.0"]加入您的project.clj即可使用它。

(ns example 
    (:require [jayq.core :refer [$]])) 

($ "tr[data-id=1]") 

(感谢yonki您指出引号是必要的。)

3

冷静下来的家伙,这是可能容易。检查验证码:

(sel1 "tr[data-id=\"1\"]")

有一个在你的HTML代码<tr data-id="1">。您看到data-id值是用引号引起来的。你只需在你的选择器中加入引号,一切都会好的。 \"是引号引起来的。希望这是可以理解的。

最后:Dommy在需要时使用querySelectorAll,因此您可以使用浏览器能够识别的每个CSS选择器。

+1

你是对的。 'querySelectorAll'要求属性值在引号中,这就是为什么它不起作用。其他库在解析选择器时更宽松,这很好。 (顺便说一句,您可以在选择器中使用单引号以避免必须使用双引号:'(sel1“tr [data-id ='1']”)'。) –

0

这种方法也可以工作!

(ns dosync2.core 
    (:require [dommy.utils :as utils] 
      [dommy.core :as dommy] 
      [dommy.attrs :as dattr]) 
    (:use-macros 
    [dommy.macros :only [node sel sel1]])) 

(defn select-by-tag-and-attr-value [the-tag the-attr the-attr-value] 
    (let [tag-selection (sel the-tag)] 
    (filter #(= the-attr-value (dattr/attr % the-attr)) tag-selection) 
    ) 
) 

(. js/console (log (clj->js (select-by-tag-and-attr-value :tr :data-id 1))))