编辑:在尝试了不同的手工解决方案之后,我正在使用JSPlumb并尝试使其在视觉上将一个列表中的单击项与另一个列表中的单击项连接起来(请参见屏幕快照)。
我在此Stackoverflow thread的基础上构建并使其基本工作,但是那里提供的代码允许多个连接,即JSPlumb绘制了多个端点和线,如果首先单击“目标”,它不会做出反应。 但是,在我的情况下,严格来说应该只有一个连接,并且当我单击任一侧的另一个列表项时,JSPlumb应该重新连接。 (例如,我单击“源1”和“目标3”,JSPlumb绘制连接。我单击“目标4”,JSPlumb应将“源1”保留为源,并将“目标4”重新设置为目标,例如现在从“源1”到“目标4”绘制连接。单击不同的“源”也是如此,即目标应保持不变。)
我需要以哪种方式更改代码以实现所需的重画?
jQuery(document).ready(function () {
var targetOption = {
anchor: "LeftMiddle",
isSource: false,
isTarget: true,
reattach: true,
endpoint: "Dot",
connector: ["Bezier", {
curviness: 50}],
setDragAllowedWhenFull: true
};
var sourceOption = {
tolerance: "touch",
anchor: "RightMiddle",
maxConnections: 1,
isSource: true,
isTarget: false,
reattach: true,
endpoint: "Dot",
connector: ["Bezier", {
curviness: 50}],
setDragAllowedWhenFull: true
};
jsPlumb.importDefaults({
ConnectionsDetachable: true,
ReattachConnections: true,
Container: 'page_connections'
});
//current question clicked on
var questionSelected = null;
var questionEndpoint = null;
//remember the question you clicked on
jQuery("#select_list_lebensbereiche ul > li").click( function () {
//remove endpoint if there is one
if( questionSelected !== null )
{
jsPlumb.removeAllEndpoints(questionSelected);
}
//add new endpoint
questionSelected = jQuery(this)[0];
questionEndpoint = jsPlumb.addEndpoint(questionSelected, sourceOption);
});
//now click on an answer to link it with previously selected question
jQuery("#select_list_wirkdimensionen ul > li").click( function () {
//we must have previously selected question
//for this to work
if( questionSelected !== null )
{
//create endpoint
var answer = jsPlumb.addEndpoint(jQuery(this)[0], targetOption);
//link it
jsPlumb.connect({ source: questionEndpoint, target: answer });
//cleanup
questionSelected = null;
questionEndpoint = null;
}
});
});
答案 0 :(得分:1)
您已经在全局变量中跟踪链接项的“源”端;一种实现所需行为的方法通常只需要以相同的方式跟踪“目标”端即可。 (有改进的空间-全局变量可能不是理想的策略,“源”和“目标”点击处理程序之间存在一些代码重复,但这至少应该用于演示。)
// ...other init variables skipped
var questionEndpoints = []; // 'source' and 'target' endpoints
// "source" click handler
jQuery("#select_list_lebensbereiche ul > li").click(function() {
//remove existing start endpoint, if any:
jsPlumb.deleteEndpoint(questionEndpoints[0]);
// add a new one on the clicked element:
questionEndpoints[0] = jsPlumb.addEndpoint(jQuery(this), sourceOption);
connectEndpoints();
});
// "target" endpoint
jQuery("#select_list_wirkdimensionen ul > li").click(function() {
if (!questionEndpoints[0]) return; // don't respond if a source hasn't been selected
// remove existing endpoint if any
jsPlumb.deleteEndpoint(questionEndpoints[1]);
//create a new one:
questionEndpoints[1] = jsPlumb.addEndpoint(jQuery(this), targetOption);
connectEndpoints();
});
var connectEndpoints = function() {
jsPlumb.connect({
source: questionEndpoints[0],
target: questionEndpoints[1]
});
};
});